配置服务文件:
1、添加中间件的重命名方法
2、boot 方法中调用添加中间件
#packages/liuning/my-first-laravel-package/src/LiuNingLaravelPackageServiceProvider.php
// boot 方法中添加如下代码
public function boot()
{
// ...
$this->addMiddlewareAlias('liuning.api', ApiAuthMiddleware::class);
// ...
}
# 添加中间件的别名方法
protected function addMiddlewareAlias($name, $class)
{
$router = $this->app['router'];
// 判断aliasMiddleware是否在类中存在
if (method_exists($router, 'aliasMiddleware')) {
// aliasMiddleware 顾名思义,就是给中间件设置一个别名
return $router->aliasMiddleware($name, $class);
}
return $router->middleware($name, $class);
$router->aliasMiddleware($name, $class);
执行完相当于在app/Http/Kernel.php中注册了中间件