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

$request->getAttribute('id') is returning null #76

Closed reiniermybeats closed 1 year ago

reiniermybeats commented 1 year ago

In the readme example Controllers as a services:

class UserController
{
    private $userRepository;

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

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

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

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

it show to get the route attribute id using $request->getAttribute('id') but if i use this method i get null returned.

my route is created like this:

$app->post('/my/{name}', MyController::class)->setName('my-name');

and the controller looks like this:

public function __invoke(ResponseInterface $response, ServerRequestInterface $request): ResponseInterface
{
    $name = $request->getAttribute('name');

The only way to get the name argument in my case is like this:

$attributes = $request->getAttributes();
$arguments = ($attributes["__route__"])->getArguments();
$name = $arguments['name'];

I understand I can also get it like this, so it's injected from the __invoke method parameters:

public function __invoke(ResponseInterface $response, ServerRequestInterface $request, $name): ResponseInterface
{
    $test = 'My name is ' . $name; // 

But the readme makes me believe the other way is also possible, somehow.

Is the readme wrong or is there some way to achieve this?

juherr commented 1 year ago

Hi,

I have the same issue. Any update about it?

KevinMarques commented 9 months ago

Is this really correct @mnapoli?

As stated in the Slim official documentation:

With PSR-7 it is possible to inject objects/values into the request object for further processing. In your applications middleware often need to pass along information to your route closure and the way to do it is to add it to the request object via an attribute.

So you can for example have a middleware which sets in the request an attribute called "user" and have also a route with a "user" named argument, causing PHP-DI Slim bridge to override the original attribute value.

The Slim documented way to access route parameters is with $route->getArgument('id') function, so maybe the original issue here was the PHP-DI slim bridge documentation indicating a missuse of getAttribute function.