我创建了一个名为PathParser的中间件类,它运行于每个请求上。其目的是处理“虚荣心URL路径”的请求,我们允许用户在我们之前的应用程序中创建这些路径。例如:用户创建了一个URL路径,如:http://example.com/i-love-this-place
PathParser所做的是检查404响应,然后查看URL路径是否匹配我们以前的虚荣心路径之一。如下所示:
class PathParser
{
public function handle($request, Closure $next, $guard = null)
{
$next_response = $next($request);
$status_code = $next_response->getStatusCode();
if ($status_code === 404) {
$script_url = $request->server("SCRIPT_URL");
$vanity_controller = new VanityController();
$found_vanity_id = Search::findVanityPath($script_url);
if (!empty($found_vanity_id)) {
$next_response = response()->make($vanity_controller->one($found_vanity_id));
}
}
return $next_response;
}
}假设如下:
在Kernel.php中,我有以下内容:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\PathParser::class,
//\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];在$middleware数组中,我尝试添加StartSession和ShareErrorsFromSession (取消对上面两行的注释),这部分起作用。但是有两个主要问题:
是否有一种方法既可以检查所有请求上的路由,又能获得经过身份验证的用户,同时也可以保留$errors?
我有一种感觉,我对请求生命周期不太了解,无法成功。但也许有办法?
如果无法满足我的要求,那么使用302重定向到标准化的前缀路径(例如http://example.com/vanity/i-love-this-place)是一个很好的解决方案)。但我希望还有别的办法。
发布于 2016-12-24 06:02:44
有几个建议:
如果您不需要auth/session/etc,那么您可以在应用程序的异常处理程序中处理Symfony\Component\HttpKernel\Exception\NotFoundHttpException异常。
在app/Exceptions/Handler.php中,修改render()方法如下所示:
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
// your code that returns a Response
}
return parent::render($request, Exception $e);
}如果您确实需要auth/session/etc,我建议在路由文件的末尾创建一个“跟踪所有”路由。例如,作为routes/web.php文件中的最后一行,放置:
Route::any('{catchall}', 'VanityController@handle')->where('catchall', '(.*)');然后,在VanityController中,有一个类似于以下内容的handle方法:
public function handle(Request $request, $url)
{
// logic to search and render your vanity page for $url
// if no vanity page was found:
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
}https://stackoverflow.com/questions/41308101
复制相似问题