laravel 5.4控制器中间件构造不起作用

时间:2017-11-13 18:10:05

标签: laravel-5.4

我有一些代码:

AController

class AController extends Controller
{

    public function __construct()
    {

        echo 'outside - AController';
        echo '<br/>';

        $this->middleware(function ($request, $next) {

            echo 'inside - AController';
            echo '<br/>';

            return $next($request);
        });

    }

    public function handle()
    {

        $B = new BController;
        if ( $B->check() ) {
            $controller = BController::class;
            $action = 'index';
        } else {
            $controller = BController::class;
            $action = 'nothing';
        }

        $container = app();
        $route = $container->make(Route::class);
        $controllerInstance = $container->make($controller);

        return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);

    }

}

BController

class BController extends Controller
{

    public function __construct()
    {

        echo 'outside - BController';
        echo '<br/>';

        $this->middleware(function ($request, $next) {

            echo 'inside - BController';
            echo '<br/>';

            return $next($request);
        });

    }

}

当从AController调用BController时,在浏览器中显示:

外面 - AController

里面 - AController

外面 - BController

为什么BController中的中间件从AController调用时没有显示出来?

外面 - AController

里面 - AController

外面 - BController

inside - BController

1 个答案:

答案 0 :(得分:0)

在路由中使用中间件而不是在控制器中使用构造。 这是laravel docs https://laravel.com/docs/5.5/middleware