'PHP Slim 4 getting Request (Psr\Http\Message\RequestInterface) everywhere
I find useful to access to the app settings everywhere in the code. So I put in the container
// array passed to DI\ContainerBuilder−>addDefinition()
return [
...
'settings' => function () {
return require __DIR__ . '/settings.php';
},
...
];
My question is : how can I access to the request (Psr\Http\Message\RequestInterface) 'every where in my code' ? Using the same mechanism or may be there is something simpler I missed ?
==== update ====
To be more accurate as it is asked by Nima, I like the way Slim handles error (http://www.slimframework.com/docs/v4/middleware/error-handling.html), so I used it a lot !
use Slim\Exception\HttpForbiddenException;
...
// security issue for example, somewhere deeeeeeeep in the code
if ($this_is_denied)
throw new HttpForbiddenException($request, 'no way !');
Well Slim\Exception needs '$request' as an argument. That is the point of my question...
==== conclusion ====
Thanks to Nima it is a bad practise :/ (cf comments below) , so forget it ! Kind Regards
Solution 1:[1]
You can create your own instance of Request for example in index.php and then pass it to anything you need:
use Slim\Factory\ServerRequestCreatorFactory;
....
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
....
$app->run($request);//Yes, it accepts an instance of ServerRequestInterface
For example, you can set it to container. Here I use PHP-DI
use DI\Container;
...
$container = new Container();
$container->set('request', $request);
// OR
$container->set(RequestInterface::class', $request);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kostiantyn |
