Closed dennis-fedco closed 3 years ago
Maybe the best way would be to have a service class PathBuilder
. This logic would separated from the router dispatcher. You would then have:
$r->addRoute('GET', PathBuilder::make('/users'), 'get_all_users_handler');
The PathBuilder class would return /users or /extra_directory/users depending on your environment. What do you think?
See https://github.com/nikic/FastRoute/issues/110#issuecomment-273760186 for some information on this. The tl;dr is that FastRoute doesn't handle this (it gets a URL and assumes all necessary preprocessing is already applied). The way to handle something like this is to strip the prefix beforehand (rather than adding it to all routes). Usually this functionality is already provided by the HTTP abstraction layer you use (something like Symfony HTTP foundation). If you use this router standalone you can strip it using the function from the linked comment.
Thank you.
The way I currently handled it is akin to aromot's comment, as I haven't figured out how to do the stripping in my environment. I had a partial solution using stripping using Zend Expressive, but in my case my prefixes had more folders in the path and thus more complicated and the end I implemented the additive solution, where I add a different prefix for local
and for dev
, and prod
. Namely something like so:
/**
* Where I use $_SERVER['SERVER_NAME'] to compute route_prefix and write it to config
*
* @var \Interop\Container\ContainerInterface $container
*/
$prefix = $container->get('config')['route_prefix'];
/** @var \Zend\Expressive\Application $app */
$app->get($prefix . '/users', App\Action\GetUsersAction::class, 'get_all_users_handler');
I do want to ask why stripping the prefix beforehand is the way to handle this issue. For, if it is, I will try the stripping again.
Groups should also help with this - but you probably already figured this out by now :laughing:
Closing here :+1:
on my local environment I have this route:
and it works great. But on my DEV, the code resides in an
extra_directory
, so the above route does not work. To make it work on DEV I would have to rewrite the above route like so:In other words, routing gives me an absolute path, and using an extra folder breaks my routing between different web server setups. Is there a way to make both work, without keeping two different code versions?
A work-around also is to keep both routes in the same code version.