这是在PHP中实现"按合同设计"模式的正确方法吗?

gre*_*emo 5 php design-patterns datacontract

我发现了"按合同设计"模式以及如何在PHP中实现.我无法在PHP中找到如何执行此操作的真实示例.第一个问题是我正在以正确的方式做到这一点吗?第二个是为什么断言回调不被尊重?

Asserts可重用断言的静态类:

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

用法:

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.');
Run Code Online (Sandbox Code Playgroud)

仅触发(右)警告:

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

Jas*_*ell 4

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

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

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

assert_options(ASSERT_BAIL,     false);
Run Code Online (Sandbox Code Playgroud)

异常将被抛出,因此看起来它在抛出异常之前就停止了执行。

希望有帮助