Symfony验证器模块无法自动加载注释

时间:2018-02-02 04:15:18

标签: php symfony validation

我正在运行symfony / validator v3.4.4独立版,我正在尝试验证对象,并且遇到了一个错误,其中doctrine无法找到验证注释类。

我错过了什么?

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
 */

提前致谢

1 个答案:

答案 0 :(得分:1)

我在测试之前遇到了同样的错误,我想传递实际的验证器而不是模拟器。

可以通过调用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) {
  }
}
*/

我不确定为什么会发生这种情况,但由于某些原因,在自动加载器中注册该类是不够的。似乎注释不会触发它们自动加载或类似的东西。