gpt4 book ai didi

php - 在 MVC 中处理 404 错误的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-03 07:47:54 25 4
gpt4 key购买 nike

所以我编写了我的 PHP MVC 框架,并有 Dispatcher 类可以实例化适当的 Controller 类并调用定义的方法传递参数。

现在在 Dispatcher 中检查此 Controller 是否存在以及方法是否存在,如果 Controller 或方法不存在我该怎么办?

目前我只返回打印 404 - Page not found 的 HTTP 对象。
但是我无法从应用程序内部自定义此消息,我想为用户提供一种无需编辑调度程序即可自定义 404 消息的方法。

总是让错误 Controller 在出现错误时被实例化,并且会加载让我们说 Error404.html View 文件的好方法是什么?
因此,用户将能够自定义此 View 文件以适合他们的应用程序设计。

有没有其他方法可以实现这一目标?什么是从调度程序返回错误的最佳方式,并让正在使用该 MVC 的“用户”或开发人员轻松自定义 404 和其他消息?

谢谢!

最佳答案

因为我不知道你的 API,所以我猜。让我们假设您的应用程序中有一个引导阶段,当调度程序被实际使用时。就像是:
$dispatcher->dispatch( $request );
然后为了处理请求,尝试访问这些 Controller 中不存在的 Controller 或方法,您可以执行以下操作:

try
{
$dispatcher->dispatch( $request );
}
catch ( ClassNotFoundException $e )
{
$dispatcher->dispatch( new Request('/error/404/controller'));
}
catch ( MethodNotFoundException $e )
{
$dispatcher->dispatch( new Request('/error/404/method'));
}
ClassNotFoundException可以由您的类加载器抛出,而调度程序本身将始终负责抛出 MethodNotFoundException .

您可以使用 method_exists() 检查 Controller 是否具有特定方法, 在您的调度程序中执行它之前。

P.S. in my humble opinion, the Dispatcher conept is better suited for event driven architectures and not for MVC-inspired patterns in web applications.

关于php - 在 MVC 中处理 404 错误的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com