首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PHP-DI的超薄:无法从自动加载器中找到类

使用PHP-DI的超薄:无法从自动加载器中找到类
EN

Stack Overflow用户
提问于 2021-08-27 17:38:59
回答 1查看 92关注 0票数 0

我正在尝试从Slim附带的pimple容器切换到PHP-DI,但我遇到了一个让自动装配正常工作的问题。由于我被限制使用PHP5.6,所以我使用Slim 3.9.0和PHP-DI 5.2.0以及PHP -di/slim bridge 1.1。

我的项目结构是这样的:

代码语言:javascript
复制
api
 - src
 |    - Controller
 |    |  - TestController.php
 |    - Service
 |    - Model
 |    - ...
 - vendor
 - composer.json

api/composer.json中,我运行了composer dumpautoload,设置了以下内容

代码语言:javascript
复制
{
    "require": {
        "slim/slim": "3.*",
        "php-di/slim-bridge": "^1.1"
    },

    "autoload": {
        "psr-4": {
            "MyAPI\\": "src/"
        }
    }
}

我的api/src/Controller/TestController.php文件只包含一个类:

代码语言:javascript
复制
<?php
namespace MyAPI\Controller;

class TestController
{ 
    public function __construct() 
    {
        
    }
    
    public function test($request,$response)
    {
        return $response->write("Controller is working");
    }
}

我最初尝试使用最小的设置来使自动装配正常工作,只使用默认配置。index.php

代码语言:javascript
复制
<?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();

但是,这将返回错误:

代码语言:javascript
复制
Type: Invoker\Exception\NotCallableException 
Message: 'TestController'is neither a callable nor a valid container entry

我只有两种方法可以让它工作,一种是直接将TestController类放在index.php中(这让我觉得PHP-DI不能很好地使用自动加载器),另一种是使用下面的\DI\Bridge\Slim\App扩展。然而,由于我需要显式地注册控制器类,这有点违背了使用自动装配的意义(除非我错过了要点):

代码语言:javascript
复制
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();
EN

回答 1

Stack Overflow用户

发布于 2021-09-02 12:47:13

如果要调用测试方法,则语法为:

代码语言:javascript
复制
 $app->get('/', TestController::class .':test');
 // or 
 $app->get('/', 'TestController:test');

而不是

代码语言:javascript
复制
$app->get('/', TestController::class ,':test');

cf https://www.slimframework.com/docs/v3/objects/router.html#container-resolution

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68957455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档