问题描述
我有一个不是symfony2项目的遗留项目,但是有symfony2组件可用。
I have a legacy project that is not a symfony2 project, yet has the symfony2 components available.
我有Doctrine实体,我想要能够断言他们通过注释。我没有容器,不能打电话:
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);
推荐答案
您可以通过以下方式初始化验证器:
You can initialize the Validator via:
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator()
您通过以下方式验证一个实体:
And you validate an entity via:
$violations = $validator->validate($entity);
如果 $ violation
是一个空数组,该实体已验证,否则您将获得违规行为,并可以:
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());
}
}
您断言您的实体,并确保所有注释被使用。我使用的遗留项目没有包含 @Entity
注释,虽然没有打扰Doctrine,但确实扰乱了验证过程。
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;
...
最后,您必须自行加载注释。 Doctrine不会使用默认的自动装载机,您必须具体使用 Doctrine\Common\Annotations\AnnotationRegistry
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"
);
这篇关于如何在传统的PHP项目中使用symfony2验证器组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!