【问题标题】:Choosing an appropriate Zend Framework exception class选择合适的 Zend Framework 异常类
【发布时间】:2013-02-07 06:35:29
【问题描述】:

使用 Zend 框架,如果传递的参数对于该方法来说是非法的,我想在模型类中的特定方法内抛出异常。例如,在 Java 中,我会这样做:

public void addName(String name) {
 if (name.equals('')) {
  throw new IllegalArgumentException();
 }
 // Other code if everything is ok.
} 

然而,据我所知,PHP 和 Zend Framework 缺少像 IllegalArgumentException 这样的基本内置异常类。那么我应该使用什么来正确传递一个实际描述出了什么问题的异常呢?自己创建这样的异常类?但这不是框架应该消除的这种代码吗?

我刚刚开始学习 Zend 框架。我一生中没有写过很多 PHP,所以请随时向我解释一些您认为对于一个体面的 PHP 程序员来说应该是显而易见的事情。

【问题讨论】:

    标签: zend-framework


    【解决方案1】:

    这里是PHP SPL exception class 中的可用例外列表。

    Exception
         LogicException
             BadFunctionCallException
             BadMethodCallException
             DomainException
             InvalidArgumentException
             LengthException
             OutOfRangeException
         RuntimeException
             OutOfBoundsException
             OverflowException
             RangeException
             UnderflowException
             UnexpectedValueException
    

    Zend Framework 的Zend_Exception 只是 PHP 内置异常的包装器,但大多数主要组件都有一个可调用的异常类。

    例如:

    public function setId($id)
        {
            $validator = new My_Validator_Id();
            if ($validator->isValid($id)) {
                $this->id = $id;
                return $this;
            } else {
                throw new Zend_Validate_Exception("$id is not a valid value for the ID field.");
            }
        }
    

    或使用 PHP 的内置异常:

    public function __get($name)
        {
            $property = strtolower($name);
    
            if (!property_exists($this, $property)) {
                throw new \InvalidArgumentException(
                    "Getting the property '$property' is not valid for this entity");
            }
            //truncated...
        }
    

    Zend Framework 2 提供了更具体的exceptions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多