Search code examples
laravellaravel-5.3lumenlumen-5.4

Lumen/Laravel - use custom router


Is there any out of the box solution without changing core to add custom router in to laravel or lumen. I already know that lumen is using different router from laravel, so I am wondering is there any possibility builded in core to change router?


Solution

  • I had the same question today. After some research I found a solution which will impact the core classes minimal.

    Note: The following description is based on Lumen 6.2.

    Before you start; think about a proper solution, using a middleware.

    Because of the nature of this framework, there is no way to use a custom Router without extending core classes and modifying the bootstrap.

    Follow these steps to your custom Router:

    Hacky solution

    1. Create your custom Router.

    Hint: In this example App will be the root namespace of the Lumen project.

    <?php
    
    namespace App\Routing;
    
    class Router extends \Laravel\Lumen\Routing\Router
    {
        public function __construct($app)
        {
            dd('This is my custom router!');
            parent::__construct($app);
        }
    }
    

    There is no Interface or similar, so you have to extend the existing Router. In this case, just a constructor containing a dd() to demonstrate, if the new Routerist going to be used.

    2. Extend the Application

    The regular Router will be initialized without any bindings or depentency injection in a method call inside of Application::__construct. Therefore you cannot overwirte the class binding for it. We have to modify this initialization proccess. Luckily Lumen is using a method just for the router initialization.

    <?php
    
    namespace App;
    
    use App\Routing\Router;
    
    class Application extends \Laravel\Lumen\Application
    {
        public function bootstrapRouter()
        {
            $this->router = new Router($this);
        }
    }
    

    3. Tell Lumen to use our Application

    The instance of Applicationis created relativley close at the top of our bootstrap/app.php.

    Find the code block looking like

    $app = new Laravel\Lumen\Application(
        dirname(__DIR__)
    );
    

    and change it to

    $app = new App\Application(
        dirname(__DIR__)
    );
    

    Proper solution

    The $router property of Application is a public property. You can simply assign an instance of your custom Router to it.

    After the instantiation of Application in your bootstrap/app.php place a

    $app->router = new \App\Routing\Router;
    

    done.