我正在尝试从Slim附带的pimple容器切换到PHP-DI,但我遇到了一个让自动装配正常工作的问题。由于我被限制使用PHP5.6,所以我使用Slim 3.9.0和PHP-DI 5.2.0以及PHP -di/slim bridge 1.1。
我的项目结构是这样的:
api
- src
| - Controller
| | - TestController.php
| - Service
| - Model
| - ...
- vendor
- composer.json在api/composer.json中,我运行了composer dumpautoload,设置了以下内容
{
"require": {
"slim/slim": "3.*",
"php-di/slim-bridge": "^1.1"
},
"autoload": {
"psr-4": {
"MyAPI\\": "src/"
}
}
}我的api/src/Controller/TestController.php文件只包含一个类:
<?php
namespace MyAPI\Controller;
class TestController
{
public function __construct()
{
}
public function test($request,$response)
{
return $response->write("Controller is working");
}
}我最初尝试使用最小的设置来使自动装配正常工作,只使用默认配置。index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '/../../api/vendor/autoload.php';
$app = new \DI\Bridge\Slim\App;
$app->get('/', TestController::class, ':test');
$app->run();但是,这将返回错误:
Type: Invoker\Exception\NotCallableException
Message: 'TestController'is neither a callable nor a valid container entry我只有两种方法可以让它工作,一种是直接将TestController类放在index.php中(这让我觉得PHP-DI不能很好地使用自动加载器),另一种是使用下面的\DI\Bridge\Slim\App扩展。然而,由于我需要显式地注册控制器类,这有点违背了使用自动装配的意义(除非我错过了要点):
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
use function DI\factory;
class MyApp extends \DI\Bridge\Slim\App
{
public function __construct() {
$containerBuilder = new ContainerBuilder;
$this->configureContainer($containerBuilder);
$container = $containerBuilder->build();
parent::__construct($container);
}
protected function configureContainer(ContainerBuilder $builder)
{
$definitions = [
'TestController' => DI\factory(function (ContainerInterface $c) {
return new MyAPI\Controller\TestController();
})
];
$builder->addDefinitions($definitions);
}
}
$app = new MyApp();
$app->get('/', ['TestController', 'test']);
$app->run();发布于 2021-09-02 12:47:13
如果要调用测试方法,则语法为:
$app->get('/', TestController::class .':test');
// or
$app->get('/', 'TestController:test');而不是
$app->get('/', TestController::class ,':test');cf https://www.slimframework.com/docs/v3/objects/router.html#container-resolution
https://stackoverflow.com/questions/68957455
复制相似问题