router
router copied to clipboard
"mount" one by one
How do I use "mount" one by one? The last one cancels the previous one.
$router->mount('/api/v1', function () use ($router) {});
doesn't work
$router->mount('/api/v2', function () use ($router) {});
works
Seems to work using Bramus version 1.6
and PHP 7.4.21
(if your project is not up-to-date, try ⇾ composer update
)
<?php
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
$router->mount('/api/v1', function () use ($router) {
$router->get('/', function() { echo 'API version 1 overview'; });
$router->get('add', function() { echo 'API version 1 add something'; });
});
$router->mount('/api/v2', function () use ($router) {
$router->get('/', function() { echo 'API version 2 overview'; });
$router->get('add', function() { echo 'API version 2 add something'; });
});
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
echo "404";
});
// Run it!
$router->run();
Sorry, I forgot one small detail, but very important
$router->mount('/api/v1', function () use ($router) {
$router->setNamespace('Api\v1'); // !!!
$router->get('/', function() { echo 'API version 1 overview'; });
$router->get('add', function() { echo 'API version 1 add something'; });
});
$router->mount('/api/v2', function () use ($router) {
$router->setNamespace('Api\v2'); // !!!
$router->get('/', function() { echo 'API version 2 overview'; });
$router->get('add', function() { echo 'API version 2 add something'; });
});
The second "setNamespace" overrides the previous one and ends up with the wrong path to the class
You're right. The current project structure does not allow that because setNamespace
defines just a class-variable. To fix that, you need to move getNamespace
. Please consider making a pull request to support the project 😉
You're right. The current project structure does not allow that because
setNamespace
defines just a class-variable. To fix that, you need to movegetNamespace
. Please consider making a pull request to support the project 😉