Skip to content

Commit 279d8d6

Browse files
committed
Adding a section about keeping BC in a re-usable bundle
1 parent 280440e commit 279d8d6

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
@@ -328,6 +328,43 @@ semantic configuration described in the cookbook.
328328
If you are defining services, they should also be prefixed with the bundle
329329
alias.
330330

331+
Custom Validation Constraints
332+
-----------------------------
333+
334+
Starting with Symfony 2.5, a new Validation API was introduced. In fact,
335+
there are 3 modes, which the user can configure in their project:
336+
337+
* 2.4: the original 2.4 and earlier validation API;
338+
* 2.5: the new 2.5 and later validation API;
339+
* 2.5-BC: the new 2.5 API with a backwards-compatible layer so that the
340+
2.4 API still works. This is only available in PHP 5.3.9+.
341+
342+
As a bundle author, you'll want to support *both* API's, since some users
343+
may still be using the 2.4 API. Specifically, if your bundle adds a violation
344+
directly to the :class:`Symfony\Component\Validator\Context\ExecutionContext`
345+
(e.g. like in a custom validation constraint), you'll need to check for which
346+
API is being used. The following code, would work for *all* users::
347+
348+
class ContainsAlphanumericValidator extends ConstraintValidator
349+
{
350+
public function validate($value, Constraint $constraint)
351+
{
352+
if ($this->context instanceof ExecutionContextInterface) {
353+
// the 2.5 API
354+
$this->context->buildViolation($constraint->message)
355+
->setParameter('%string%', $value)
356+
->addViolation();
357+
);
358+
} else {
359+
// the 2.4 API
360+
$this->context->addViolation(
361+
$constraint->message,
362+
array('%string%' => $value)
363+
);
364+
}
365+
}
366+
}
367+
331368
Learn more from the Cookbook
332369
----------------------------
333370

0 commit comments

Comments
 (0)