How to use closures in validation component in Symfony2?
Would you share with me an example how to use closures in validation component in Symfony2?
I use this code to validate $prop:
use Symfony\Component\Validator\Constraints as Assert;
cla开发者_JS百科ss A
{
/**
* @Assert\NotBlank()
* @Assert\Choice(choices = {"value1", "value2"})
*/
private $prop;
}
I want to use closure here as shown in documentation with "callback" option. I've googled for a while but haven't found any examples yet.
In order to use a closure you'll have to define your validation metadata using PHP (as opposed to YAML, XML or annotations). For an example, take a look at the "PHP" tab of the first example on the page you linked to. It uses loadValidatorMetadata
.
Here's how it would look with a callback set:
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\Choice;
class Author
{
protected $gender;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Choice(
'message' => 'Choose a valid gender',
'callback' => function () {
return array('male', 'female');
},
));
}
}
As you can see, it doesn't really work very well. The main issue is that the static loadValidatorMetadata
method does not really have any access to the outside world.
If you insist on using closures you could create a separate implementation of the Symfony\Component\Validator\Mapping\Loader\LoaderInterface
. But honestly, the easiest is to just use callback with an instance method name, as the example shows with getGenders
.
精彩评论