我在webman的Index類中寫構(gòu)造函數(shù),代碼如下
<?php
namespace app\controller;
use support\Request;
use think\facade\Db;
class Index
{
public function _construct()
{
echo "this is index _construct";
}
public function index(Request $request)
{
return response('hello webman');
}
}
在User類中也寫構(gòu)造方法
<?php
namespace app\controller;
use support\Request;
use think\facade\Db;
class User
{
public function _construct()
{
echo "this is user _construct";
}
public function login(Request $request)
{
return response('hello webman');
}
}
當(dāng)php start.php start 的時候,在命令行會輸出
this is index __construct,
然后我再次訪問(多次訪問)http://127.0.0.1:8787/index/index的時候,此時也不會輸出 this is index _construct,說明此時構(gòu)造函數(shù)不再執(zhí)行;
當(dāng)我訪問http://127.0.0.1:8787/user/index的時候,命令行會輸出兩次
this is user __construct,
當(dāng)再次(多次)訪問時,不會再輸出this is user _construct
說明此時的構(gòu)造函數(shù)不在執(zhí)行;
我想咨詢一下,這是什么原因造成的?如果我們想利用構(gòu)造函數(shù)每次都執(zhí)行的特點,那么應(yīng)該如何利用呢?
construct只能顯示一個下劃線,所以只寫了一個
webman是常駐內(nèi)存框架,controller 初始化后會被復(fù)用,不會每次請求都初始化一次 。
如果你需要每個請求前或者請求后都做一些事情,可以用中間鍵來做。
例如:創(chuàng)建文件 app\middleware\ActionHook.php
(middleware目錄不存在請自行創(chuàng)建)
<?php
namespace app\middleware;
use support\bootstrap\Container;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class ActionHook implements MiddlewareInterface
{
public function process(Request $request, callable $next) : Response
{
if ($request->controller) {
$controller = Container::get($request->controller);
if (method_exists($controller, 'beforeAction')) {
$before_response = call_user_func([$controller, 'beforeAction'], $request);
if ($before_response instanceof Response) {
return $before_response;
}
}
$response = $next($request);
if (method_exists($controller, 'afterAction')) {
$after_response = call_user_func([$controller, 'afterAction'], $request, $response);
if ($after_response instanceof Response) {
return $after_response;
}
}
return $response;
}
return $next($request);
}
}
在 config/middleware.php 中添加如下配置
return [
'' => [
// .... 這里省略了其它配置 ....
app\middleware\ActionHook::class
]
];
這樣如果 controller包含了 beforeAction 或者 afterAction方法會自動被調(diào)用。