首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP DRY抛出InvalidArgumentException

PHP DRY抛出InvalidArgumentException
EN

Stack Overflow用户
提问于 2013-05-03 19:57:24
回答 1查看 753关注 0票数 3

在我正在构建的框架中,我正朝着使我的代码更具可测试性的方向发展,因为我以前沉迷于MVC+Singleton模式,并且拥有大量的静态类。从那时起,我开始对单元测试和测试驱动开发有了更多的了解,所以它促使我对很多代码进行了重构。这种重构的一部分驱使我尝试并正确地使用PHP中的扩展类,即不仅抛出Exception类,而且抛出更多相关的异常。

我有以下类:

代码语言:javascript
复制
<?php

namespace Framework;

class Uri {

    public static function new_from_http() {

        $uri = '';

        if (isset($_SERVER['REQUEST_URI'])) {
            $uri = $_SERVER['REQUEST_URI'];
        } elseif (isset($_SERVER['PATH_INFO'])) {
            $uri = $_SERVER['PATH_INFO'];
        }

        return static::new_from_string($uri);
    }

    public static function new_from_string($string) {

        return new static(explode('/', $string));
    }

    protected $uri = [];

    public function __construct(array $uri) {

        $this->uri = array_values(array_filter($uri));
    }

    public function get_segment($offset, $default = null) {

        if (!is_int($offset)) {
            throw new \InvalidArgumentException(
                sprintf('%s requires argument 1 to be an integer, %s given.',
                    __METHOD__,
                    gettype()
                )
            );
        }

        return isset($this->uri[$offset - 1])
            ? $this->uri[$offset - 1]
            : $default;
    }
}

这一切都很好,正如您所看到的,get_segment方法需要一个整数,否则它将抛出InvalidArgumentException。问题是,我想创建更多的方法,这些方法也需要整数作为参数,我不想到处剪切和粘贴代码。合并所有这些类型的参数检查的最佳选项是什么,以便我可以在不同的类和方法中使用它们,同时保持消息彼此一致。

我的一个想法是扩展框架命名空间下的异常类,并让构造函数接受不同的参数,例如:

代码语言:javascript
复制
namespace Framework;

class InvalidArgumentException extends \InvalidArgumentException {

    public function __construct($method, $argument, $value) {

        parent::__construct(
            sprintf('%s requires argument 1 to be an integer, %s given.',
                $method,
                gettype($value)
            )
        );
    }
}

它的名称如下:

代码语言:javascript
复制
if (!is_int($arg)) {

    throw new \Framework\InvalidArgumentException(__METHOD__, 1, $arg);
}

还可以改进的是,\Framework\InvalidArgumentException可以通过回溯获得__METHOD__值。

我还有其他选择吗?最好的选择是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-04 00:06:42

否则,我会将/InvalidArgumentException扩展到NonIntegerException中,做基本上相同的事情。通过这种方式,如果您想要使用stringsarrays或任何其他类型,您可以创建新的异常,并且不必使用疯狂的逻辑来确定要使用哪条消息。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16358404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档