我收到此错误:
消息:"[语义错误]属性User :: $ name中的注释"@Symfony\Component\Validator\Constraints\Length"不存在,或者无法自动加载."
这是Github上的代码https://github.com/symfony/Validator
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
class User {
/**
* @Assert\Length(min = 3)
* @Assert\NotBlank
*/
private $name;
/**
* @Assert\Email
* @Assert\NotBlank
*/
private $email;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
/**
* @Assert\True(message = "The user should have a Google Mail account")
*/
public function isGmailUser()
{
return false !== strpos($this->email, '@gmail.com');
}
}
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
$user = new User('John Doe', 'john@example.com');
$violations = $validator->validate($user);
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Doctrine不使用自动加载PHP,您必须使用autoloadRegistry注册:
AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "path/to/symfony/library/validator");
Run Code Online (Sandbox Code Playgroud)
使用 Symfony\Component\Validator\Constraints 作为断言;
/**
* @var float $weight
*
* @ORM\Column(name="weight", type="decimal",precision=3,scale=2, nullable=true)
*
* @Assert\Range(
* min = "90",
* max = "350",
* minMessage = "You must weight at least 90",
* maxMessage = "You cannot weight more than 300"
* )
* @Assert\NotBlank(groups={"group one","goup 2"})
* @Assert\Regex(pattern= "/[0-9]/",message="Require number only")
*/
private $weight=0;
Run Code Online (Sandbox Code Playgroud)