Slim Callable UserController不存在RuntimeException

Sha*_*sir 4 php model-view-controller slim

嗨,我是新来的苗条我坚持这个任何人的帮助请

routes.php文件

$app->get('/', 'UserController:index');
Run Code Online (Sandbox Code Playgroud)

dependencis.php

$container['src\UserController'] = function ($container) {
    return new \src\UserController($container->get('settings'));
};
Run Code Online (Sandbox Code Playgroud)

UserController.php

namespace App\Controllers;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use App\src\Controller;
class UserController extends Controller {
    public function index(Request $request, Response $response) {
        return $this->db;
    }
}
Run Code Online (Sandbox Code Playgroud)

controller.php

namespace App\src;

class Controller {
    protected $container;
    public function __construct($c) {
        $this->container = $c;
    }

    public function __get($property) {
        if($this->container->has($property)) {
            return $this->container->get($property);
        }
        return $this->{$property};
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*len 11

正如您已将路线定义为:

$app->get('/', 'UserController:index');
Run Code Online (Sandbox Code Playgroud)

然后,您需要将DI工厂定义为:

$container['UserController'] = function ($container) {
    // return an instantiated UserController here.
};
Run Code Online (Sandbox Code Playgroud)

您还应该查看名称空间和PSR-4如何将名称空间名称映射到目录.通常,src命名空间名称中从不存在,但是您确实看到了一个名称空间,例如App映射到srccomposer.json中指定的Composer自动加载器中的目录调用.

通常,它看起来像这样:

"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},
Run Code Online (Sandbox Code Playgroud)

这意味着您有一个目录,src并且该目录中的任何类都将具有基本命名空间,App然后任何其他目录充当子命名空间.

即如果你有一个名为的文件src/Controllers/UserController.php,那么该文件中的类定义将是:

<?php
namespace App\Controllers;
class UserController
{
    // methods here
}
Run Code Online (Sandbox Code Playgroud)

另请注意,文件名的大小写与类名匹配,并且目录的大写形式与子名称空间的大小写相匹配.

继续这个例子,我希望DI工厂看起来像这样:

$container['UserController'] = function ($container) {
    return new \App\Controllers\UserController($container->get('settings'));
};
Run Code Online (Sandbox Code Playgroud)

src在命名空间定义中看到它是非常不寻常的,因此请检查磁盘上的命名空间和文件是否都匹配,因为问题中的代码不一致.