结论:thinkphp6.0控制器中间件,在initialize()之后执行
测试:
1、首先创建一个tp6的新项目
composer create-project topthink/think tp
2、安装多应用模式扩展
composer require topthink/think-multi-app
3、创建一个新应用
php think build index
4、创建一个中间件
php think make:middleware index@Test
5、在app\index\middleware\Test.php中添加测试代码
<?php
declare (strict_types = 1);
namespace app\index\middleware; use think\Response;
class Test
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
$request->test_name = 'hello world';
dump('中间件');
return $next($request);
}
}
6、在app\index\controller\Index.php中添加测试代码
<?php
declare (strict_types = 1);
namespace app\index\controller;
use app\BaseController;
use app\index\middleware\Test;
use app\Request;
use think\App;
class Index extends BaseController
{
protected $middleware = [
Test::class,
];
public function initialize()
{
parent::initialize();
dump('initialize:' . $this->request->test_name);
}
protected function getTestName()
{
dump($this->request->test_name);
}
public function index(Request $request)
{
$this->getTestName();
echo 'index';
}
}
7、在项目根目录下面执行:
php think run
8、在浏览器中访问http://127.0.0.1:8000
看到如下结果:
由此可知tp6的控制器中间件,在initialize()之后执行,在initialize()中是获取不到中间件中设置的test_name的