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

问题描述 投票:1回答:1

我已经基于SlimPHP团队的Slim Skeleton应用程序建立了一个新应用程序。在我的路由定义中,我希望能够以described in the Slim4 documentation的身份访问路由解析器。因此,例如,我希望能够编辑骨架的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()。但是此刻,我会为所有可行的方法感到满意。

php slim php-di slim-4
1个回答
0
投票

苗条的骨架实际上演示了您需要实现的示例。创建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;
});
© www.soinside.com 2019 - 2024. All rights reserved.