虽然building multi-tenancy packages for Laravel 5我必须找出如何从代码中动态添加中间件。与this question on SO相比,我不想触及Http / Kernel定义。
在应用程序初始化期间,我检查数据库中是否已知所请求的主机名,以及该主机名是否需要重定向到主主机名或ssl。
因为您不想将Http/Kernel
作为一个包接触,我们需要使用服务提供商。
要求:
答案 0 :(得分:4)
解决方案是在内核中动态注册中间件。首先编写中间件,例如:
<?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);
如果您对此实施有疑问,请添加评论。