3

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

simedia
  • 213
  • 2
  • 7
  • Route callbacks and middlewares receive the request object as an argument. Where else so you need the request object? Please provide more details. – Nima Jul 25 '20 at 14:48
  • The example you provide (a custom error handler) is a function that receives `$request` from Slim as first argument. – Álvaro González Jul 25 '20 at 18:26
  • Indeed, so how to get the request like a 'global' var ? – simedia Jul 25 '20 at 21:06
  • 2
    Simply, just don't do it. Request object is immutable, so if you keep a so called _global_ copy of it, whenever a middleware or some part of code makes some changes to the request you'll get a new request object, and you'll need to replace that global copy with the new one. That is an error prone process and contradicts your initial intentions. Just pass the request down the chain of function calls, no matter how deep the chain gets. – Nima Jul 26 '20 at 04:49
  • Thanks Nima for the advice. Finally I am not surprised as I read this in the doc. I guest I reach the Slim's twisting limit in this case. Anyway it is still a very neat framework – simedia Jul 26 '20 at 16:21

1 Answers1

0

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);
Kostiantyn
  • 1,792
  • 2
  • 16
  • 21