router icon indicating copy to clipboard operation
router copied to clipboard

"mount" one by one

Open milkamil93 opened this issue 3 years ago • 4 comments

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

milkamil93 avatar Aug 02 '21 16:08 milkamil93

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();

uvulpos avatar Aug 03 '21 17:08 uvulpos

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

milkamil93 avatar Aug 04 '21 07:08 milkamil93

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 😉

uvulpos avatar Aug 04 '21 17:08 uvulpos

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 😉

https://github.com/bramus/router/pull/158

milkamil93 avatar Aug 05 '21 07:08 milkamil93