概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:50:08 | 135 次阅读 | 评论: 0 | 来源: 网络整理

The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you’re using validation with forms, this means that you can make these custom errors display next to a specific field, instead of simply at the top of your form.

This process works by specifying one or more callback methods, each of which will be called during the validation process. Each of those methods can do anything, including creating and assigning validation errors.

注解

A callback method itself doesn’t fail or return any value. Instead, as you’ll see in the example, a callback method has the ability to directly add validator “violations”.

Applies to class
Options
Class Callback
Validator CallbackValidator

Configuration

  • YAML
    # src/Acme/BlogBundle/Resources/config/validation.yml
    AcmeBlogBundleEntityAuthor:
        constraints:
            - Callback: [validate]
    
  • Annotations
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorConstraints as Assert;
    use SymfonyComponentValidatorContextExecutionContextInterface;
    // if you're using the older 2.4 validation API, you'll need this instead
    // use SymfonyComponentValidatorExecutionContextInterface;
    
    class Author
    {
        /**
         * @AssertCallback
         */
        public function validate(ExecutionContextInterface $context)
        {
            // ...
        }
    }
    
  • XML
    <!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    
        <class name="AcmeBlogBundleEntityAuthor">
            <constraint name="Callback">validate</constraint>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraints as Assert;
    
    class Author
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addConstraint(new AssertCallback('validate'));
        }
    }
    

The Callback Method

The callback method is passed a special ExecutionContextInterface object. You can set “violations” directly on this object and determine to which field those errors should be attributed:

// ...
use SymfonyComponentValidatorContextExecutionContextInterface;
// if you're using the older 2.4 validation API, you'll need this instead
// use SymfonyComponentValidatorExecutionContextInterface;

class Author
{
    // ...
    private $firstName;

    public function validate(ExecutionContextInterface $context)
    {
        // somehow you have an array of "fake names"
        $fakeNames = array(/* ... */);

        // check if the name is actually a fake name
        if (in_array($this->getFirstName(), $fakeNames)) {
            // If you're using the new 2.5 validation API (you probably are!)
            $context->buildViolation('This name sounds totally fake!')
                ->atPath('firstName')
                ->addViolation();

            // If you're using the old 2.4 validation API
            /*
            $context->addViolationAt(
                'firstName',
                'This name sounds totally fake!'
            );
            */
        }
    }
}

Static Callbacks

You can also use the constraint with static methods. Since static methods don’t have access to the object instance, they receive the object as the first argument:

public static function validate($object, ExecutionContextInterface $context)
{
    // somehow you have an array of "fake names"
    $fakeNames = array(/* ... */);

    // check if the name is actually a fake name
    if (in_array($object->getFirstName(), $fakeNames)) {
        // If you're using the new 2.5 validation API (you probably are!)
        $context->buildViolation('This name sounds totally fake!')
            ->atPath('firstName')
            ->addViolation()
        ;

        // If you're using the old 2.4 validation API
        $context->addViolationAt(
            'firstName',
            'This name sounds totally fake!'
        );
    }
}

External Callbacks and Closures

If you want to execute a static callback method that is not located in the class of the validated object, you can configure the constraint to invoke an array callable as supported by PHP’s call_user_func function. Suppose your validation function is VendorPackageValidator::validate():

namespace VendorPackage;

use SymfonyComponentValidatorContextExecutionContextInterface;
// if you're using the older 2.4 validation API, you'll need this instead
// use SymfonyComponentValidatorExecutionContextInterface;

class Validator
{
    public static function validate($object, ExecutionContextInterface $context)
    {
        // ...
    }
}

You can then use the following configuration to invoke this validator:

  • YAML
    # src/Acme/BlogBundle/Resources/config/validation.yml
    AcmeBlogBundleEntityAuthor:
        constraints:
            - Callback: [VendorPackageValidator, validate]
    
  • Annotations
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorConstraints as Assert;
    
    /**
     * @AssertCallback({"VendorPackageValidator", "validate"})
     */
    class Author
    {
    }
    
  • XML
    <!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    
        <class name="AcmeBlogBundleEntityAuthor">
            <constraint name="Callback">
                <value>VendorPackageValidator</value>
                <value>validate</value>
            </constraint>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraints as Assert;
    
    class Author
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addConstraint(new AssertCallback(array(
                'VendorPackageValidator',
                'validate',
            )));
        }
    }
    

注解

The Callback constraint does not support global callback functions nor is it possible to specify a global function or a service method as callback. To validate using a service, you should create a custom validation constraint and add that new constraint to your class.

When configuring the constraint via PHP, you can also pass a closure to the constructor of the Callback constraint:

// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;

use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraints as Assert;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $callback = function ($object, ExecutionContextInterface $context) {
            // ...
        };

        $metadata->addConstraint(new AssertCallback($callback));
    }
}

Options

callback

type: string, array or Closure [default option]

The callback option accepts three different formats for specifying the callback method:

  • A string containing the name of a concrete or static method;
  • An array callable with the format array('<Class>', '<method>');
  • A closure.

Concrete callbacks receive an ExecutionContextInterface instance as only argument.

Static or closure callbacks receive the validated object as the first argument and the ExecutionContextInterface instance as the second argument.

payload

type: mixed default: null

2.6 新版功能: The payload option was introduced in Symfony 2.6.

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to.

For example, you may want to used several error levels to present failed constraint differently in the front-end depending on the severity of the error.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务