[英]Symfony validator module the annotation could not be auto loaded
I am running symfony/validator v3.4.4 standalone and am trying to validate objects and am running into an error where doctrine is unable to locate the validation annotation classes. 我正在独立运行symfony / validator v3.4.4,并尝试验证对象,并且遇到了一个错误,即学说无法找到验证注释类。
What am I missing? 我想念什么?
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
require_once('vendor/autoload.php');
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
class Foo {
/**
* @Assert\NotBlank()
*/
public $userId;
function __construct($userId) {
$this->userId = $userId;
}
}
class Bar {}
$foo = new Foo(1);
$bar = new Bar();
var_dump($validator->validate($bar));
/**
* =>
* object(Symfony\Component\Validator\ConstraintViolationList)#22 (1) {
* ["violations":"Symfony\Component\Validator\ConstraintViolationList":private]=>
* array(0) {
* }
* }
*/
var_dump($validator->validate($foo));
/**
* =>
* Fatal error: Uncaught exception
* 'Doctrine\Common\Annotations\AnnotationException'
* with message '[Semantical Error] The annotation
* "@Symfony\Component\Validator\Constraints\NotBlank" in property Foo::$userId
* does not exist, or could not be auto-loaded.' in
* /home/readitla/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php:54
*/
Thanks in advance 提前致谢
I've had the same error before in tests where I wanted to pass the actual validator instead of a mock. 在测试中,我想通过实际的验证器而不是模拟程序时遇到了相同的错误。
The problem can be fixed by calling class_exists(Assert\\NotBlank::class)
: 可以通过调用
class_exists(Assert\\NotBlank::class)
来解决此问题:
<?php
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
require_once __DIR__ . '/vendor/autoload.php';
class_exists(Assert\NotBlank::class);
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
class Foo
{
/**
* @Assert\NotBlank()
*/
public $id;
}
$foo = new Foo();
$foo->id = 123;
var_dump($validator->validate($foo));
/*
object(Symfony\Component\Validator\ConstraintViolationList)#20 (1) {
["violations":"Symfony\Component\Validator\ConstraintViolationList":private]=>
array(0) {
}
}
*/
I'm not exactly sure why this happens, but for some reason registering the class in the autoloader is not enough. 我不确定为什么会发生这种情况,但是由于某种原因,在自动加载器中注册该类还不够。 It seems that annotations do not trigger them to be autoloaded or something like that.
注释似乎不会触发它们自动加载或类似的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.