简体   繁体   中英

How does Laravel know about Middlewares of packages by auto discovery?

Searched for this information and I couldn't find anything. Only github links and some info but about service providers not middlewares.

I saw something about registering middlewares in service providers, but it's not the point.

I mean.

This package - laravel-page-speed

As I read, auto discovery takes registration of service providers from composer.json.

Okay, but there is no word about middlewares.

So maybe this package?

public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/laravel-page-speed.php' => config_path('laravel-page-speed.php'),
        ]);
    }
    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/laravel-page-speed.php', 'laravel-page-speed.php');
    }

I don't see anything about middlewares, so maybe this config? I won't put here all the code, but too, nothing about it. Just enable package and skipped extensions.

So how?

This package uses and brings in several middlewares, but doesn't register them anywhere.

Without auto-discovery we need to type them on our own. But with auto discovery we haven't and I don't see anywhere in the package to register them.

So just I need explanation how this works.

How this middlewares actually are registered to work?

I don't think those extra middlewares are auto-registered. Looking at Github documentation you could think so but I believe this is only matter of not best markdown formatting for readme because in case you would like to publish configuration file you still need to run:

php artisan vendor:publish --provider="RenatoMarinho\LaravelPageSpeed\ServiceProvider"

although you could think you need to do it only in Laravel < 5.5

At current Date (08.2018) they're not auto registered in this package you mention (laravel-page-speed).

I know two ways to register middlewares in Laravel 5.6 from within a package.

This will push the middleware to the global $middlewares array from App\\Http\\Kernel and will be executed before the route middleware groups ($middlewareGroups eg 'web').

$kernel = app()->make(Kernel::class);
$kernel->pushMiddleware(YourMiddleware::class);

This will push the middleware to the route middleware groups array from App\\Http\\Kernel $middlewareGroups and will be executed after the global $middlewares:

$router = app()->make(Router::class);
$router->pushMiddlewareToGroup('web', YourMiddleware::class);

So that means if you need to access the session, you need to push it to the middelwareGroups.

Hope it helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM