This forum is in READ-ONLY mode.
You can look around, but if you want to ask a new question, please use Stack Overflow.

Custom form constraint dependency injection (used in CI)

Discuss Symfony 2 bundles here

Custom form constraint dependency injection (used in CI)

by patriots21 » Wed Sep 10, 2014 9:11 am

We have an application built on top of Codeigniter (don't ask me why CI, it is what it is) and have recently started using more Symfony components to prepare the application for a total port to Symfony someday in the future.

I have successfully gotten Symfony Form to work with the project as well as the Symfony Validator. I've gotten around writing my own validation constraints and this can be done easily enough even without the symfony framework until you get to a point where you need to inject a dependency (such as the doctrine entityManager) into the validator. According to this awesome cookbook ... raint.html , this can be done like so:

Constraint Validators with Dependencies¶
If your constraint validator has dependencies, such as a database connection, it will need to be configured as a service in the dependency injection container. This service must include the validator.constraint_validator tag and an alias attribute:
Code: Select all
    ->register('validator.unique.your_validator_name', 'Fully\Qualified\Validator\Class\Name')
    ->addTag('validator.constraint_validator', array('alias' => 'alias_name'));

We obviously don't have the DI container that symfony has but we have been using Pimple as our DI container. Can't figure out how to do this properly. Right now I got the entity manager injected into the validator by making use of the CI_instance and one of our bootstrap classes.
Code: Select all
class IsUsernameUniqueValidator extends ConstraintValidator
     * The entity manager
    private $em;

    public function __construct()
        $this->em = get_instance()->kernel->serviceContainer['entity_manager'];

    public function validate($value, Constraint $constraint)
        $user = $this->em->getRepository('Acme\Entities\User')
                                ->findOneBy(['username' => $value]);
                array('%string%' => $value)

The disadvantage of this of course is that this validator class is coupled with Codeigniter. As much as possible we try to keep CI specific code in the controllers and no where else.
Junior Member
Posts: 1
Joined: Wed Sep 10, 2014 8:54 am