PHP Slim 4 getting Request (Psr\Http\Message\RequestInterface) everywhere

1.3k Views Asked by At

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

1

There are 1 best solutions below

0
On

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);