laravel 5 的动态中间件

Dynamic middleware for laravel 5

虽然 building multi-tenancy packages for Laravel 5 I had to find out how to add middleware dynamically from code. In comparison to 我不想触及 Http/Kernel 定义。

在应用程序初始化期间,我检查请求的主机名在数据库中是否已知,以及此主机名是否需要重定向到主主机名或 ssl。

因为不想把Http/Kernel作为一个包来碰,所以我们需要使用服务商。

要求:

解决方法是在内核中动态注册中间件。先写你的中间件,比如:

<?php namespace HynMe\MultiTenant\Middleware;

use App;
use Closure;
use Illuminate\Contracts\Routing\Middleware;

class HostnameMiddleware implements Middleware
{
    public function handle($request, Closure $next)
    {
        /* @var \HynMe\MultiTenant\Models\Hostname */
        $hostname = App::make('HynMe\Tenant\Hostname');
        if(!is_null($redirect = $hostname->redirectActionRequired()))
            return $redirect;

        return $next($request);
    }
}

现在在您的 service provider 中使用以下代码 boot() 方法将此中间件添加到内核中:

$this->app->make('Illuminate\Contracts\Http\Kernel')->prependMiddleware('HynMe\MultiTenant\Middleware\HostnameMiddleware');

回答 redirectActionRequired() 方法在主机名对象中的作用:

/**
 * Identifies whether a redirect is required for this hostname
 * @return \Illuminate\Http\RedirectResponse|null
 */
public function redirectActionRequired()
{
    // force to new hostname
    if($this->redirect_to)
        return $this->redirectToHostname->redirectActionRequired();
    // @todo also add ssl check once ssl certificates are support
    if($this->prefer_https && !Request::secure())
        return redirect()->secure(Request::path());

    // if default hostname is loaded and this is not the default hostname
    if(Request::getHttpHost() != $this->hostname)
        return redirect()->away("http://{$this->hostname}/" . (Request::path() == '/' ? null : Request::path()));

    return null;
}

如果您需要动态注册 routeMiddleware,请在您的服务提供商中使用以下内容;

$this->app['router']->middleware('shortname', Vendor\Some\Class::class);

如果您对此实施有疑问,请添加评论。