How to use the symfony2 validator component in a l

2019-08-07 18:03发布

I have a legacy project that is not a symfony2 project, yet has the symfony2 components available.

I have Doctrine entities, and I want to be able to assert them via annotations. I do not have a container and cannot just call:

$container->get('validator')->validate($entity);

1条回答
男人必须洒脱
2楼-- · 2019-08-07 18:39

You can initialize the Validator via:

$validator = Validation::createValidatorBuilder()
                    ->enableAnnotationMapping()
                    ->getValidator()

And you validate an entity via:

$violations = $validator->validate($entity);

If $violations is an empty array, the entity was validated, otherwise you will get the violations and can:

if (count($violations) > 0)
    foreach($violations as $violation) {
         $this->getLogger()->warning($violation->getMessage());
    }
}

You assert your entity and make sure that all the annotations are used. The legacy project I was using e.g. did not include the @Entity annotation, and while it didn't bother Doctrine, it did bother the validation process.

<?php
namespace Hive\Model\YourEntity;

use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\Table;
use Symfony\Component\Validator\Constraints\NotNull;

/**
 * Class AdGroupAd
 * @Entity(repositoryClass="YourEntityRepository")
 * @Table(name="your_entity_table_name")
 */
class AdGroupAd
{
     ...

    /**
     * @Column(type="string")
     * @var string
     * @NotNull()
     */
    protected $status;

    ...

And finally, you must autload the annotations. Doctrine will not use the default autoloader, you have to specifically use the Doctrine\Common\Annotations\AnnotationRegistry

You can do it via:

AnnotationRegistry::registerAutoloadNamespace(
    "Symfony",
    PATH_TO_YOUR_WEB_ROOT . "/vendor/symfony/symfony/src"
);
查看更多
登录 后发表回答