如何使用 Slim-Skeleton 中演示的 PHP-DI 设置访问 slim4 的 routeParser?

How to access slim4's routeParser with the PHP-DI setup demonstrated in Slim-Skeleton?

我已经根据 SlimPHP 团队的 Slim Skeleton application. Inside of my route definitions, I want to be able to access the route parser as described in the Slim4 documentation. So, for example, I'd like to be able to edit the skeleton's app/routes.php 文件设置了一个新的应用程序,如下所示:

    $app->get('/', function (Request $request, Response $response) {
        $routeParser = $app->getRouteCollector()->getRouteParser();  // this doesn't work
        $response->getBody()->write('Hello world! ' . $routeParser->urlFor('something'));
        return $response;
    });

$app->getRouteCollector()->getRouteParser() 不起作用是有道理的,因为此处未定义 $app。但我认为我们应该改为调用 $this->getRouteCollector()->getRouteParser();,但这会给出错误:"Call to undefined method DI\Container::getRouteCollector()"

看来我的困惑肯定是关于依赖注入,这对我来说是新的,而且对我来说不是很自然。老实说,我很想在其他地方(在 index.php? 内)定义 $routeParser 变量,这样我就可以在任何路由定义中访问它,而不必每次都调用 $app->getRouteCollector()->getRouteParser() .但此刻我会满足于任何有效的方法。

Slim skeleton 实际上演示了您需要实现的示例。创建App实例后in index.php,有这样的赋值:

// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
$callableResolver = $app->getCallableResolver();

你也可以这样做:

$routeParser = $app->getRouteCollector()->getRouteParser();

如果你真的需要这个 RouteParser 实例在每个路由回调中可用,你可以把它放在依赖容器中,比如:

$container->set(Slim\Interfaces\RouteParserInterface::class, $routeParser);

然后你可以使用 PHP-DI 自动连接功能将这个 RouteParser 注入到控制器构造函数中:

use Slim\Interfaces\RouteParserInterface;
class SampleController {
    public function __construct(RouteParserInterface $routeParser) {
        $this->routeParser = $routeParser;
        //...
    }
}

或者如果您需要在任何路由回调中调用 $container->get()

$app->get('/', function (Request $request, Response $response) {
    $routeParser = $this->get(Slim\Interfaces\RouteParserInterface::class);
    $response->getBody()->write('Hello world! ' . $routeParser->urlFor('something'));
    return $response;
});