PHP-DI / Slim-Bridge

PHP-DI integration with the Slim framework
http://php-di.org/doc/frameworks/slim.html
MIT License
176 stars 38 forks source link

PHP-DI - SLIM - Request/Response Object Availability #58

Closed zabakala closed 3 years ago

zabakala commented 4 years ago

Hi. Thanks for the wonderful product. There is a clear example:

use Psr\Http\Message\{RequestInterface as Request, ResponseInterface as Response};

class UserController
{
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function delete(Request $request, Response $response)
    {
        $this->userRepository->remove($request->getAttribute('id'));

        $response->getBody()->write('User deleted');
        return $response;
    }
}

$app->delete('/user/{id}', ['UserController', 'delete']);

However, I seem to lack the following functionality or, perhaps, it is there, but not documented. Inside PHP-DI definition file, I would like to distribute the content of the Request/Response entities via constructor injections to both the UserRepository above as well as to other entities inside the PHP-DI definition file. ... I tried injecting via the UserRepository constructor, but it, unexpectedly, errors out saying: the class is not instantiable. Is injecting Request/Response via dependencies constructor possible (just like, for example, in Symfony, Nette etc.) just like it is via the delete method above?

mnapoli commented 4 years ago

@davidgithub1980 It isn't possible to inject the request and response inside services.

This is because those objects have a different lifecycle than services. Services are stateless. Request and response are state. Said another way: injecting the request and response is not really a good practice.

The only workaround would be to introduce a "RequestStack" service like in Symfony, but you have to create everything by yourself.