Skip to content

Commit 62f8ffe

Browse files
committed
Adding a section about keeping BC in a re-usable bundle
1 parent 09ae39d commit 62f8ffe

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

cookbook/bundles/best_practices.rst

+37
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,43 @@ semantic configuration described in the cookbook.
268268
If you are defining services, they should also be prefixed with the bundle
269269
alias.
270270

271+
Custom Validation Constraints
272+
-----------------------------
273+
274+
Starting with Symfony 2.5, a new Validation API was introduced. In fact,
275+
there are 3 modes, which the user can configure in their project:
276+
277+
* 2.4: the original 2.4 and earlier validation API;
278+
* 2.5: the new 2.5 and later validation API;
279+
* 2.5-BC: the new 2.5 API with a backwards-compatible layer so that the
280+
2.4 API still works. This is only available in PHP 5.3.9+.
281+
282+
As a bundle author, you'll want to support *both* API's, since some users
283+
may still be using the 2.4 API. Specifically, if your bundle adds a violation
284+
directly to the :class:`Symfony\Component\Validator\Context\ExecutionContext`
285+
(e.g. like in a custom validation constraint), you'll need to check for which
286+
API is being used. The following code, would work for *all* users::
287+
288+
class ContainsAlphanumericValidator extends ConstraintValidator
289+
{
290+
public function validate($value, Constraint $constraint)
291+
{
292+
if ($this->context instanceof ExecutionContextInterface) {
293+
// the 2.5 API
294+
$this->context->buildViolation($constraint->message)
295+
->setParameter('%string%', $value)
296+
->addViolation();
297+
);
298+
} else {
299+
// the 2.4 API
300+
$this->context->addViolation(
301+
$constraint->message,
302+
array('%string%' => $value)
303+
);
304+
}
305+
}
306+
}
307+
271308
Learn more from the Cookbook
272309
----------------------------
273310

0 commit comments

Comments
 (0)