Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Validator
  4. Loading Resources
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • The StaticMethodLoader
  • The File Loaders
  • The AnnotationLoader
  • Using Multiple Loaders
  • Caching
  • Using a Custom MetadataFactory

Loading Resources

Edit this page

Loading Resources

The Validator component uses metadata to validate a value. This metadata defines how a class, array or any other value should be validated. When validating a class, the metadata is defined by the class itself. When validating simple values, the metadata must be passed to the validation methods.

Class metadata can be defined in a configuration file or in the class itself. The Validator component collects that metadata using a set of loaders.

See also

You'll learn how to define the metadata in Metadata.

The StaticMethodLoader

The most basic loader is the StaticMethodLoader. This loader gets the metadata by calling a static method of the class. The name of the method is configured using the addMethodMapping() method of the validator builder:

1
2
3
4
5
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    ->addMethodMapping('loadValidatorMetadata')
    ->getValidator();

In this example, the validation metadata is retrieved executing the loadValidatorMetadata() method of the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class User
{
    protected $name;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new Assert\NotBlank());
        $metadata->addPropertyConstraint('name', new Assert\Length([
            'min' => 5,
            'max' => 20,
        ]));
    }
}

Tip

Instead of calling addMethodMapping() multiple times to add several method names, you can also use addMethodMappings() to set an array of supported method names.

The File Loaders

The component also provides two file loaders, one to load YAML files and one to load XML files. Use addYamlMapping() or addXmlMapping() to configure the locations of these files:

1
2
3
4
5
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    ->addYamlMapping('validator/validation.yaml')
    ->getValidator();

Note

If you want to load YAML mapping files, then you will also need to install the Yaml component.

Tip

Just like with the method mappings, you can also use addYamlMappings() and addXmlMappings() to configure an array of file paths.

The AnnotationLoader

At last, the component provides an AnnotationLoader to get the metadata from the annotations of the class. Annotations are defined as @ prefixed classes included in doc block comments (/** ... */). For example:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Validator\Constraints as Assert;
// ...

class User
{
    /**
     * @Assert\NotBlank
     */
    protected $name;
}

To enable the annotation loader, call the enableAnnotationMapping() method. If you use annotations instead of attributes, it's also required to call addDefaultDoctrineAnnotationReader() to use Doctrine's annotation reader:

1
2
3
4
5
6
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    ->enableAnnotationMapping()
    ->addDefaultDoctrineAnnotationReader() // add this only when using annotations
    ->getValidator();

To disable the annotation loader after it was enabled, call disableAnnotationMapping().

Note

In order to use the annotation loader, you should have installed the doctrine/annotations and doctrine/cache packages with Composer.

Tip

Annotation classes aren't loaded automatically, so you must load them using a class loader like this:

1
2
3
4
5
6
7
8
9
use Composer\Autoload\ClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;

/** @var ClassLoader $loader */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

return $loader;

Using Multiple Loaders

The component provides a LoaderChain class to execute several loaders sequentially in the same order they were defined:

The ValidatorBuilder will already take care of this when you configure multiple mappings:

1
2
3
4
5
6
7
8
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    ->enableAnnotationMapping(true)
    ->addDefaultDoctrineAnnotationReader()
    ->addMethodMapping('loadValidatorMetadata')
    ->addXmlMapping('validator/validation.xml')
    ->getValidator();

Caching

Using many loaders to load metadata from different places is convenient, but it can slow down your application because each file needs to be parsed, validated and converted into a ClassMetadata instance.

To solve this problem, call the setMappingCache() method of the Validator builder and pass your own caching class (which must implement the PSR-6 interface CacheItemPoolInterface):

1
2
3
4
5
6
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    // ... add loaders
    ->setMappingCache(new SomePsr6Cache())
    ->getValidator();

Note

The loaders already use a singleton load mechanism. That means that the loaders will only load and parse a file once and put that in a property, which will then be used the next time it is asked for metadata. However, the Validator still needs to merge all metadata of one class from every loader when it is requested.

Using a Custom MetadataFactory

All the loaders and the cache are passed to an instance of LazyLoadingMetadataFactory. This class is responsible for creating a ClassMetadata instance from all the configured resources.

You can also use a custom metadata factory implementation by creating a class which implements MetadataFactoryInterface. You can set this custom implementation using setMetadataFactory():

1
2
3
4
5
6
use Acme\Validation\CustomMetadataFactory;
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
    ->setMetadataFactory(new CustomMetadataFactory(...))
    ->getValidator();

Caution

Since you are using a custom metadata factory, you can't configure loaders and caches using the add*Mapping() methods anymore. You now have to inject them into your custom metadata factory yourself.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:

    Symfony 6.2 is backed by

    Symfony 6.2 is backed by

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Jean-Christophe Cuvelier, a Symfony contributor

    Thanks Jean-Christophe Cuvelier for being a Symfony contributor

    1 commit • 5 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia