New in Symfony 2.4: A better Callback constraint

Sometimes, we make things more complex than they should be; the Callback
constraint was such an example, and using it in Symfony 2.4 is much simpler,
feels more natural, and is more powerful at the same time.

The Callback constraint is a great way to define custom validation rules
without the need to create custom constraints and validator classes. You just
need to create one or more methods that does the validation and generates some
violations. But before 2.4, the constraint needs to be attached to the class
itself instead of the validation method(s), leading to some verbose
configuration (in all configuration formats):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

useSymfony\Component\Validator\ExecutionContextInterface;/** * @Assert\Callback(methods={ * { "Acme\BlogBundle\MyStaticValidatorClass", "isAuthorValid"} * }) */classAuthor{// ...publicfunctionisAuthorValid(ExecutionContextInterface$context){// somehow you have an array of "fake names"$fakeNames=array();// check if the name is actually a fake nameif(in_array($this->getFirstName(),$fakeNames)){$context->addViolationAt('firstname','This name sounds totally fake!',array(),null);}}}

As of Symfony 2.4, you can just annotate the method itself (the XML or YAML
configuration formats are also much simpler to write):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

useSymfony\Component\Validator\ExecutionContextInterface;classAuthor{// .../** * @Assert\Callback */publicfunctionisAuthorValid(ExecutionContextInterface$context){// somehow you have an array of "fake names"$fakeNames=array();// check if the name is actually a fake nameif(in_array($this->getFirstName(),$fakeNames)){$context->addViolationAt('firstname','This name sounds totally fake!',array(),null);}}}

You can now also use an external method to validate your object, in which
case, the callback will get the object to validate as a first argument: