0

我搜索了有关使用 PDO 处理异常的最佳实践,但大多数示例仅从简单的一类方法中查看。

如果我在 ORM 类型模型中使用控制器和 repo,那么各种 try/catch 和 throw 块应该在哪里发生?

一个简化的例子:

控制器:(创建 repo 对象,触发 loadProduct 方法,并加载模板)

class ProductController {
    public function viewProduct($product_id) {
        $ProductRepository = new ProductRepository($this->Pdo);
        $Product = $ProductRepository->loadProduct($product_id);
            
        include(__DIR__.'/../templates/product_template.php');
    }
}

模型/存储库:

class ProductRepository
{
    private $Pdo;
        
    public function __construct(PDO $Pdo)
    {
        $this->Pdo = $Pdo;
    }
            
    public function loadProduct($product_id,$withimages=0)
    {
        $Stm = $this->Pdo->prepare('
            SELECT p.product_id,p.model,p.price,p.prodinfo,pi.image_path
            FROM products p LEFT JOIN product_images pi
            ON p.product_id = pi.product_id
            WHERE p.product_id = :product_id
            AND pi.is_primary = 1
        ');
        $Stm->bindParam(':product_id',$product_id,PDO::PARAM_INT);
        $Stm->execute();
    
        return $this->arrayToObject($Stm->fetch(PDO::FETCH_ASSOC));    
    }
}

是否应该将 try/catch 块放入控制器中,如果execute()没有返回则抛出异常?$Pdo->prepare()如果方法没有触发,抛出一个单独的异常?

4

1 回答 1

1

In general, exceptions handling policy is very simple. Especially with PDO. Because PDO throws one only in case of serious malfunction and there is little sense in continuing execution - so, just a default halt is okay.

So, for the average part of code, be it model, repository or whatever, no dedicated handling required at all.

Only in certain places for which you have a scenario for the failed query, try-catch have to be used. Most used scenario is a transaction rollback. So, if you have transaction, you may wish to wrap it in try and then rollback in catch.

To answer a clarification in comments:

That's two essentially different scenarios:

  • There is nothing exceptional if SELECT can't find a product.
  • While if INSERT somehow creates an invalid SQL query, it's indeed a catastrophe.

and they need different handling.

For the first case you don't need no exceptions at all, it's regular behavior. Just have in your template a branch that says "Nothing found"

For the second one, create a custom exception handler, that logs error, sends 503, and shows generic 503 error page.

于 2013-11-05T19:39:29.837 回答