Closed moritz-h closed 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.
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
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