2

使用 Zend Framework,如果传递的参数对于该方法来说是非法的,我想在模型类中的特定方法内抛出异常。例如,在 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 程序员来说应该是显而易见的事情。

4

1 回答 1

2

下面是PHP SPL 异常类中可用异常的列表。

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

Zend FrameworkZend_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可用。

于 2013-02-07T06:49:11.710 回答