gpt4 book ai didi

PHP Slim 4 随处获取请求 (Psr\Http\Message\RequestInterface)

转载 作者:行者123 更新时间:2023-12-05 07:03:53 25 4
gpt4 key购买 nike

我发现在代码中随处访问应用程序设置很有用。所以我放入容器

// array passed to DI\ContainerBuilder−>addDefinition()
return [
...
'settings' => function () {
return require __DIR__ . '/settings.php';
},
...
];

我的问题是:如何访问请求 (Psr\Http\Message\RequestInterface)“我代码中的每个位置”?使用相同的机制还是我错过了更简单的东西?

====更新====

尼玛问的更准确,我喜欢Slim处理错误的方式(http://www.slimframework.com/docs/v4/middleware/error-handling.html),所以用了很多!

use Slim\Exception\HttpForbiddenException;
...
// security issue for example, somewhere deeeeeeeep in the code
if ($this_is_denied)
throw new HttpForbiddenException($request, 'no way !');

嗯,Slim\Exception 需要'$request' 作为参数。这就是我的问题的重点......

====结论====

感谢尼玛,这是一个不好的做法:/(参见下面的评论),所以算了吧!亲切的问候

最佳答案

例如,您可以在 index.php 中创建自己的 Request 实例,然后将其传递给您需要的任何对象:

use Slim\Factory\ServerRequestCreatorFactory;
....
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
....
$app->run($request);//Yes, it accepts an instance of ServerRequestInterface

比如可以设置为container。这里我使用PHP-DI

use DI\Container;
...
$container = new Container();
$container->set('request', $request);
// OR
$container->set(RequestInterface::class', $request);

关于PHP Slim 4 随处获取请求 (Psr\Http\Message\RequestInterface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63089403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com