star/validator

验证器实现库

dev-master / 0.1.x-dev 2015-02-14 12:51 UTC

This package is auto-updated.

Last update: 2024-09-12 03:38:39 UTC


README

Build Status

可以连接到任何需要验证的对象的验证工具。

用法

验证器

验证器是类,用于确定值是否有效。在以下示例中,YourNonEmptyValidator 将确保 SomeObject 上的名称不能为空。

// YourNonEmptyValidator.php
class YourNonEmptyValidator implements Validator
{
    /**
     * @var SomeObject
     */
    private $object;

    /**
     * @param SomeObject $object
     */
    public function __construct(SomeObject $object)
    {
        $this->object = $object;
    }

    /**
     * @param NotificationHandler $handler
     *
     * @return ValidationResult
     */
    public function validate(NotificationHandler $handler)
    {
        $name = $this->object->getName();

        if (empty($name)) {
            $handler->notifyError(new StringMessage('Name cannot be empty.'));
        }

        return $handler->createResult();
    }
}

验证器将返回一个 ValidationResult 以确定是否有任何约束失败。

通知处理程序

NotificationHandler 负责通知用户错误。

目前仅实现了以下策略

  • ExceptionNotificationHandler:在第一个错误时抛出 ValidationErrorException(建议用于开发)。
  • DeferredNotificationHandler:将所有错误跟踪下来,供 ValidationResult 未来使用。

示例

假设你创建了一个需要验证的类

// SomeObject.php
class SomeObject
{
    /**
     * @var string
     */
    private $name;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

你需要在其中实现一个验证方法,将所有验证器推送到 ValidationHandler

// SomeObject.php
...
/**
 * @param NotificationHandler $handler
 *
 * @return ValidationResult
 */
public function validate(NotificationHandler $handler)
{
    $validator = new YourNonEmptyValidator($this); // This is your custom validator implementing Validator interface

    return $validator->validate($handler);
}
...

创建你的对象(或使用内置验证器)的验证器,你可以从验证中获得结果。

使用结构,验证你的代码将看起来像这样。

// Using the Exception handler on a valid object
$validObject = new SomeObject();
$validObject->setName('non-empty');
$result = $validObject->validate(new ExceptionNotificationHandler());
$result->hasErrors(); // Returns false
$result->getErrors()); // Returns empty array(), since there was no errors

// Using the Exception handler on a invalid object
$invalidObject = new SomeObject();
$invalidObject->validate(new ExceptionNotificationHandler()); // Would throw an exception on the first error (because of the handler).

// Using the deferred handler on a invalid object
$result = $invalidObject->validate(new DeferredNotificationHandler());
$result->hasErrors(); // Returns true
$result->getErrors()); // Returns empty array('Name cannot be empty.')