咨询一个webman关于构造函数的问题 __construct

你好啊

我在webman的Index类中写构造函数,代码如下
<?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类中也写构造方法
<?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');
}
}

当php start.php start 的时候,在命令行会输出
this is index __construct,
然后我再次访问(多次访问)http://127.0.0.1:8787/index/index的时候,此时也不会输出 this is index _construct,说明此时构造函数不再执行;
当我访问http://127.0.0.1:8787/user/index的时候,命令行会输出两次
this is user __construct,
当再次(多次)访问时,不会再输出this is user _construct
说明此时的构造函数不在执行;
我想咨询一下,这是什么原因造成的?如果我们想利用构造函数每次都执行的特点,那么应该如何利用呢?

construct只能显示一个下划线,所以只写了一个

2499 2 1
2个回答

walkor

webman是常驻内存框架,controller 初始化后会被复用,不会每次请求都初始化一次 。
如果你需要每个请求前或者请求后都做一些事情,可以用中间键来做。

例如:创建文件 app\middleware\ActionHook.php(middleware目录不存在请自行创建)

<?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方法会自动被调用。

  • 暂无评论
你好啊

好的,多谢指点。也就是说在webman中构造函数要用中间件的方式来替代。

  • 暂无评论
年代过于久远,无法发表回答
🔝