slimphp / Slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
http://slimframework.com
MIT License
11.98k stars 1.95k forks source link

$request->getAttribute('route') in middleware is null, when route does not exist #1991

Closed moritz-h closed 7 years ago

moritz-h commented 8 years ago

Slim goes down the middleware stack also for non existent routes, before returning a 404 Response. Then $request->getAttribute('route') is null for not existent routes in the middleware. ('determineRouteBeforeAppMiddleware' is set to true)

So every time you use $request->getAttribute('route') in a middleware you must check if its null, before you access methods of the route object like $request->getAttribute('route')->getArgument(...) or $request->getAttribute('route')->getPattern()

At first i thought it is logical that the route is null, when it not exists and reported a documentation bug, to add this test in the example code: https://github.com/slimphp/Slim-Website/issues/184

But you could also argue, that if you set determineRouteBeforeAppMiddleware to true, you expect a valid route in every case.

Or perhaps Slim could provide some helper to make this "if null" test as short as possible.

(This discussion started on IRC Channel with @geggleto and is posted here for further discussion)

Minimal example is here: https://gist.github.com/moritz-h/5050e80c0ba530752701057bb8e7c703

Regards Moritz

akrabat commented 7 years ago

The operation is as expected.

We only 404 on dispatch, so that middleware has the option of changing the $request if the route attribute is null so that it can then be dispatched.

moritz-h commented 7 years ago

so that middleware has the option of changing the $request if the route attribute is null so that it can then be dispatched This makes sense. But then the documentation is wrong: The route is always available in route middleware. https://www.slimframework.com/docs/cookbook/retrieving-current-route.html

PR for documentation fix: https://github.com/slimphp/Slim-Website/pull/209