Sometimes you need to put a constraint on a whole class, rather than a single value. Duplicate usernames are a good example of this – you don’t want to be able to set a username to one that is already in use – but if it is in use with the user you are currently working on, you don’t want to flag it up as an error!
Lets use that as an example. You have a Username constraint and a UsernameValidator object to do the actual validation. We need to supply the validator an object, so we need to put the following method inside the Username object.
public function getTargets() { return self::CLASS_CONSTRAINT; }
This will turn the first parameter in our isValid function in the UsernameValidator class to an object.
public function isValid($user, Constraint $constraint)
Finally, you can call the constraint from your YAML validation file.
User: constraints: - nocs:UniqueUsername: ~
Normally, under user you would have getters and properties – but here we’re adding a new section named “constraints” which lists all the class constraints.
Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.
Tags: frameworks, PHP, symfony2, validation, yaml
This entry was posted on Saturday, March 9th, 2013 at 1:35 pm and is filed under Programming, Tech. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.