PHP-DI / Slim-Bridge

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

Request attribute not injected #25

Closed carc1n0gen closed 6 years ago

carc1n0gen commented 6 years ago

The readme describes the feature "Request attribute injection" and shows an example of how route parameters can be automatically injected in to controllers. But it seems attributes set manually with "$request->withAttribute('key', 'val');" are not injectable. Or is this as expected?

Example:

$app = new DI\Bridge\Slim\App();

$app->add(function ($request, $response, $next) {
    return $next($request->withAttribute('name', 'Bob'), $response);
});

$app->get('/', function ($name, ResponseInterface $response) {
    return $response->getBody()->write($name);
});

return $app;

This produces:

Type: Invoker\Exception\NotEnoughParametersException Message: Unable to invoke the callable because no value was given for parameter 1 ($name)

tflight commented 6 years ago

I suspect the documentation isn't using the same terminology as Slim. The documentation says "request attribute" where I think it is referring to what Slim calls "route placeholders" in their documentation and $routeArguments internally.

Of course rather than injecting the request attribute (which I don't think is possible) you can get it from the request object, which you can inject.

$app->get('/', function ($request, $response) {
    $name = $request->getAttribute('name');
    return $response->getBody()->write($name);
});

Does that sound right, @mnapoli ? If so I'd be happy to PR the Slim-Bridge docs to update the terminology.

carc1n0gen commented 6 years ago

@tflight I believe that is the workaround I ended up going with.

The reason I thought the use of attribute was the same is because internally, Slim stores route parameters in with the ->setAttribute so I figured it was all the same

mnapoli commented 6 years ago

Thank you, your analysis is right, this is caused by these lines:

https://github.com/PHP-DI/Slim-Bridge/blob/11eca37ecc0d402b1c2813de3ae2d7f50cfbc779/src/ControllerInvoker.php#L38-L47

only the $routeArguments are available for injection. All the other request attributes are ignored.

I've opened #29 to inject request attributes, please let me know if you think this is a good solution.

carc1n0gen commented 6 years ago

👍 @mnapoli The change you've made in that PR is exactly my use case!