【问题标题】:PHP factory for returning conditional objects after verification?验证后返回条件对象的PHP工厂?
【发布时间】:2013-07-23 14:03:32
【问题描述】:

我基本上需要从我的 PHP 类中调用两个构造函数之一,这取决于是否需要验证。

我当前的代码如下所示:

class Event extends Generic {

    private $user_id;

    function __construct($user_id=null) {
        $this->user_id = $user_id;
    }

    public function verify($user_id=null, $identifier=null) {

        if (parent::verifyUser($user_id, $identifier)) {
            return new Event($user_id);
        }
        else {
            // what gets retruend here in the event of a failure???
        }
    }

    public function noverify($user_id=null) {
        return new Event(user_id);
    }
}

这样调用代码:

$event = new Event();
$obj1 = $event->noverify(5);
$obj2 = $event->verify(5, 100);

如果内部条件失败,我真的不清楚我应该如何处理构造函数失败的事件。我是不是走错了路?

【问题讨论】:

    标签: php class factory


    【解决方案1】:

    我要么抛出异常,要么返回FALSE:

    else {
        throw new Exception('verification failed');
    }
    

    或

    else {
        return FALSE;
    }
    

    【讨论】:

    • 为什么是 false 而不是 null ?
    • 通常 PHP 同意如果一个函数失败应该返回false。现在几乎每个核心功能都在这样做。
    • 我认为这是从 PHP 比现在更接近 C 的时候开始的。由于应该返回一个对象,所以对我来说,在失败的情况下不返回任何东西似乎比返回布尔值更自然。此外,某些函数可能会在成功时返回 false。例如 isFeatureEnabled($feature)。如果给定了有效参数,则函数成功但仍有可能返回 false。
    • 你的假设是错误的。首先,PHP 从来没有接近于 C(C 甚至没有布尔类型),其次,在 PHP 的早期版本中,一些函数返回 NULL、-1、...一些 FALSE 出错。统一 php 核心的过程决定应该使用FALSE - 如果FALSE 不是成功的有效回报。由于 PHP 不接近 C(距离很远),因此具有不同数据类型的返回值是完全可以的。最后还有一些方法会在成功时返回 NULL,例如 User::findSingle(1) 如果 id 有效则返回用户或 NULL 如果不是则返回
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多