【问题标题】:Is this the right way of implementing "Design by contract" pattern in PHP?这是在 PHP 中实现“按合同设计”模式的正确方法吗?
【发布时间】:2011-11-28 14:33:27
【问题描述】:

我发现了“按合同设计”模式以及如何在 PHP 中实现。我找不到如何在 PHP 中执行此操作的真实示例。 第一个问题是我做对了吗? 第二个是为什么assert回调不被兑现?

用于可重用断言的静态类Asserts

class Asserts
{
    public static function absentOrNotNumeric($value)
    {
        return !isset($value) ? true : is_numeric($value);
    }
}

用法:

assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  true);
assert_options(ASSERT_CALLBACK, array('UseAsserts', 'onAssertFailure'));

class UseAsserts
{
    private $value;

    public function __construct($value)
    {
        // Single quotes are needed otherwise you'll get a
        // Parse error: syntax error, unexpected T_STRING 
        assert('Asserts::absentOrNotNumeric($value)');
        $this->value = $value;
    }

    public static function onAssertFailure($file, $line, $message)
    {
        throw new Exception($message);
    }
}

// This will trigger a warning and stops execution, but Exception is not thrown
$fail = new UseAsserts('Should fail.');

仅触发(右)警告:

警告:assert() [function.assert]:断言 “Asserts::absetOrNotNumeric($value)”失败。

【问题讨论】:

  • 它会触发什么警告?
  • @Mario 看到我的编辑,谢谢。

标签: php design-patterns datacontract


【解决方案1】:

您的异常被抛出,将其更改为:

public static function onAssertFailure($file, $line, $message)
{
    echo "<hr>Assertion Failed:
    File '$file'<br />
    Line '$line'<br />
    Code '$code'<br /><hr />";
}

导致文本显示,一些测试发现如果您更改此选项

assert_options(ASSERT_BAIL,     false);

异常会被抛出,所以它似乎在抛出异常之前就放弃了执行。

希望有帮助

【讨论】:

    【解决方案2】:

    您的代码:http://codepad.org/y10BlV8m

    我的代码:http://codepad.org/slSX3HKd

    尝试使用双引号:assert("Asserts::absentOrNotNumeric($value)");

    【讨论】:

    • 同样不,assert 需要单引号,请参阅 PHP 网站上的 assert 示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2019-09-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2012-02-16
    相关资源
    最近更新 更多