如何将自定义 404 页面添加到 Lumen(非 Laravel)应用程序

时间:2021-01-18 15:05:24

标签: php lumen

我正在构建一个 Lumen 应用程序,其中我的应用程序的部分正在使用 Lumen 库。这是一个由独立部分组成的应用程序(即组装的一些代码使用 Lumen,其他部分不使用)。我来自 Silex,您可以在那里使用库而无需成为应用程序。

我通过创建自己的 Application 类让几乎优雅地工作:

命名空间 Tsugi\Lumen;

class Application extends \Laravel\Lumen\Application {
    function __construct() {
        ...
        // Configure the storage Lumen
        $this->useStoragePath(...);

        // Add some routes
        $this->router->group([
            'namespace' => 'Koseu\Controllers',
        ], function () {
            \Koseu\Controllers\Lessons::routes($this);
            \Koseu\Controllers\Topics::routes($this);
            \Koseu\Controllers\Discussions::routes($this);
        });
    }
}

然后我使用 .htaccess 在我的 URL 层次结构中的某个点运行此代码:

    $app = new \Tsugi\Lumen\Application(...);
    $app->run();

这非常有效并且满足了我的要求,即我的 URL 空间的部分使用 Lumen,而我的 URL 空间的其他部分是其他框架或 PHP 模式。

问题是我想要我自己的 404 页面。所有其他解决方案 (a) 谈论 404.blade.php - 这是 Laravel 解决方案 - 不是纯粹的 Lumen 解决方案,(b) 谈论 App\Exceptions\Handler - 我在 Lumen 代码或文档中找不到它告诉您如何创建它或如何将其链接到我的应用程序。

如果我可以链接我自己的异常处理程序,我确切地知道我会做什么 - 我会创建我自己的扩展 Laravel\Lumen\Exceptions\Handler 的类,覆盖 render() 方法并添加我的部分,让 parent 完成剩下的工作。像这样:

namespace Tsugi\Lumen;

class Handler extends Laravel\Lumen\Exceptions\Handler {
    public function render($request, \Exception $e)
    {
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException ) {
            $txt = "Happy little 404";
            return new Response($txt, 404);
        }
        return parent::render($request, $e);
    }
}

我所缺少的只是我的 Application 构造函数中的行是一种说法:

$this->tellLumenToUseErrorHandler( '\Tsugi\Lumen\Handler' );

我很亲近。我查看了 lumen-framework/src/Concerns/RegistersExceptionHandlers.php

中的这些行
protected function resolveExceptionHandler()
{
    if ($this->bound('Illuminate\Contracts\Debug\ExceptionHandler')) {
       return $this->make('Illuminate\Contracts\Debug\ExceptionHandler');
    } else {
         return $this->make('Laravel\Lumen\Exceptions\Handler');
    }
}

而且我认为“如果我能控制这里发生的事情,我就会说服 Lumen 使用我的 Handler”。

我错过了什么?

0 个答案:

没有答案
相关问题