gpt4 book ai didi

php - Symfony2 - 触发 404 异常的最佳实践

转载 作者:行者123 更新时间:2023-12-04 00:08:04 25 4
gpt4 key购买 nike

在 Symfony 中抛出异常的最佳实践是什么?

文档中有一个很好的例子http://symfony.com/doc/current/book/controller.html#managing-errors-and-404-pages在 Controller 中抛出异常。

第二种方法是在模型中抛出异常,例如我有这个方法的实体产品:

class ProductRepository extends EntityRepository
{
public function getProductBySlug($slug)
{
$product = $this->findOneBySlug($slug);
if (is_null($product )) {
throw new NotFoundHttpException(sprintf('Unable to find product : "%s".!', $slug));
}
return $product ;
}
}

如果我会多次调用 getProductBySlug,我不会重复异常代码。有什么更好的方法?

感谢您的回答。

最佳答案

您必须将异常放入 Controller 调用的方法中,并在每个 Controller 中使用这些方法,这样您就不必复制代码。

你可以:

第一种情况提供了更简洁的代码,但增加了一点复杂性,第二种情况实现起来更快。

关于php - Symfony2 - 触发 404 异常的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989193/

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