[英]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.是否有任何开箱即用的解决方案,而无需更改核心以将自定义路由器添加到 Laravel 或 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?
我已经知道 lumen 使用的是与 laravel 不同的路由器,所以我想知道是否有可能在核心中构建来更改路由器?
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 .
注:以下描述基于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.由于这个框架的性质,如果不扩展核心类和修改引导程序,就无法使用自定义
Router
。
Follow these steps to your custom Router
:按照以下步骤操作您的自定义
Router
:
Router
. Router
。 Hint: In this example App
will be the root namespace of the Lumen project.提示:在这个例子中
App
将是 Lumen 项目的根命名空间。
<?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
.没有
Interface
或类似的东西,所以你必须扩展现有的Router
。 In this case, just a constructor containing a dd()
to demonstrate, if the new Router
ist going to be used.在这种情况下,只需一个包含
dd()
的构造函数来演示,是否要使用新的Router
。
Application
Application
The regular Router
will be initialized without any bindings or depentency injection in a method call inside of Application::__construct
.在
Application::__construct
内部的方法调用中,常规Router
将在没有任何绑定或依赖注入的情况下进行初始化。 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.
幸运的是,Lumen 使用了一种仅用于路由器初始化的方法。
<?php
namespace App;
use App\Routing\Router;
class Application extends \Laravel\Lumen\Application
{
public function bootstrapRouter()
{
$this->router = new Router($this);
}
}
Application
Application
The instance of Application
is created relativley close at the top of our bootstrap/app.php
. Application
的实例是在我们的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__)
);
The $router
property of Application
is a public property. Application
的$router
属性是公共属性。 You can simply assign an instance of your custom Router
to it.您可以简单地将自定义
Router
的实例分配给它。
After the instantiation of Application
in your bootstrap/app.php
place a在
bootstrap/app.php
的Application
实例化之后放置一个
$app->router = new \App\Routing\Router;
done.完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.