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

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

You can create a custom constraint by extending the base constraint class, Constraint. As an example you’re going to create a simple validator that checks if a string contains only alphanumeric characters.

Creating the Constraint Class

First you need to create a Constraint class and extend Constraint:

// src/AppBundle/Validator/Constraints/ContainsAlphanumeric.php
namespace AppBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;

/**
 * @Annotation
 */
class ContainsAlphanumeric extends Constraint
{
    public $message = 'The string "%string%" contains an illegal character: it can only contain letters or numbers.';
}

注解

The @Annotation annotation is necessary for this new constraint in order to make it available for use in classes via annotations. Options for your constraint are represented as public properties on the constraint class.

Creating the Validator itself

As you can see, a constraint class is fairly minimal. The actual validation is performed by another “constraint validator” class. The constraint validator class is specified by the constraint’s validatedBy() method, which includes some simple default logic:

// in the base SymfonyComponentValidatorConstraint class
public function validatedBy()
{
    return get_class($this).'Validator';
}

In other words, if you create a custom Constraint (e.g. MyConstraint), Symfony will automatically look for another class, MyConstraintValidator when actually performing the validation.

The validator class is also simple, and only has one required method validate():

// src/AppBundle/Validator/Constraints/ContainsAlphanumericValidator.php
namespace AppBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;

class ContainsAlphanumericValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!preg_match('/^[a-zA-Za0-9]+$/', $value, $matches)) {
            // If you're using the new 2.5 validation API (you probably are!)
            $this->context->buildViolation($constraint->message)
                ->setParameter('%string%', $value)
                ->addViolation();

            // If you're using the old 2.4 validation API
            /*
            $this->context->addViolation(
                $constraint->message,
                array('%string%' => $value)
            );
            */
        }
    }
}

Inside validate, you don’t need to return a value. Instead, you add violations to the validator’s context property and a value will be considered valid if it causes no violations. The buildViolation method takes the error message as its argument and returns an instance of ConstraintViolationBuilderInterface. The addViolation method call finally adds the violation to the context.

Using the new Validator

Using custom validators is very easy, just as the ones provided by Symfony itself:

  • YAML
    # src/AppBundle/Resources/config/validation.yml
    AppBundleEntityAcmeEntity:
        properties:
            name:
                - NotBlank: ~
                - AppBundleValidatorConstraintsContainsAlphanumeric: ~
    
  • Annotations
    // src/AppBundle/Entity/AcmeEntity.php
    use SymfonyComponentValidatorConstraints as Assert;
    use AppBundleValidatorConstraints as AcmeAssert;
    
    class AcmeEntity
    {
        // ...
    
        /**
         * @AssertNotBlank
         * @AcmeAssertContainsAlphanumeric
         */
        protected $name;
    
        // ...
    }
    
  • XML
    <!-- src/AppBundle/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="AppBundleEntityAcmeEntity">
            <property name="name">
                <constraint name="NotBlank" />
                <constraint name="AppBundleValidatorConstraintsContainsAlphanumeric" />
            </property>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/AppBundle/Entity/AcmeEntity.php
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraintsNotBlank;
    use AppBundleValidatorConstraintsContainsAlphanumeric;
    
    class AcmeEntity
    {
        public $name;
    
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addPropertyConstraint('name', new NotBlank());
            $metadata->addPropertyConstraint('name', new ContainsAlphanumeric());
        }
    }
    

If your constraint contains options, then they should be public properties on the custom Constraint class you created earlier. These options can be configured like options on core Symfony constraints.

Constraint Validators with Dependencies

If your constraint validator has dependencies, such as a database connection, it will need to be configured as a service in the dependency injection container. This service must include the validator.constraint_validator tag and an alias attribute:

  • YAML
    # app/config/services.yml
    services:
        validator.unique.your_validator_name:
            class: FullyQualifiedValidatorClassName
            tags:
                - { name: validator.constraint_validator, alias: alias_name }
    
  • XML
    <!-- app/config/services.xml -->
    <service id="validator.unique.your_validator_name" class="FullyQualifiedValidatorClassName">
        <argument type="service" id="doctrine.orm.default_entity_manager" />
        <tag name="validator.constraint_validator" alias="alias_name" />
    </service>
    
  • PHP
    // app/config/services.php
    $container
        ->register('validator.unique.your_validator_name', 'FullyQualifiedValidatorClassName')
        ->addTag('validator.constraint_validator', array('alias' => 'alias_name'));
    

Your constraint class should now use this alias to reference the appropriate validator:

public function validatedBy()
{
    return 'alias_name';
}

As mentioned above, Symfony will automatically look for a class named after the constraint, with Validator appended. If your constraint validator is defined as a service, it’s important that you override the validatedBy() method to return the alias used when defining your service, otherwise Symfony won’t use the constraint validator service, and will instantiate the class instead, without any dependencies injected.

Class Constraint Validator

Beside validating a class property, a constraint can have a class scope by providing a target in its Constraint class:

public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

With this, the validator validate() method gets an object as its first argument:

class ProtocolClassValidator extends ConstraintValidator
{
    public function validate($protocol, Constraint $constraint)
    {
        if ($protocol->getFoo() != $protocol->getBar()) {
            // If you're using the new 2.5 validation API (you probably are!)
            $this->context->buildViolation($constraint->message)
                ->atPath('foo')
                ->addViolation();

            // If you're using the old 2.4 validation API
            /*
            $this->context->addViolationAt(
                'foo',
                $constraint->message,
                array(),
                null
            );
            */
        }
    }
}

Note that a class constraint validator is applied to the class itself, and not to the property:

  • YAML
    # src/AppBundle/Resources/config/validation.yml
    AppBundleEntityAcmeEntity:
        constraints:
            - AppBundleValidatorConstraintsContainsAlphanumeric: ~
    
  • Annotations
    /**
     * @AcmeAssertContainsAlphanumeric
     */
    class AcmeEntity
    {
        // ...
    }
    
  • XML
    <!-- src/AppBundle/Resources/config/validation.xml -->
    <class name="AppBundleEntityAcmeEntity">
        <constraint name="AppBundleValidatorConstraintsContainsAlphanumeric" />
    </class>
    
最新网友评论  共有(0)条评论 发布评论 返回顶部

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