gpt4 book ai didi

php - 不能对属性或 getter 施加约束

转载 作者:可可西里 更新时间:2023-11-01 13:42:35 25 4
gpt4 key购买 nike

我尝试创建 custom constraint在 symfony 3 中

我有错误

约束 App\Bundle\MyBundle\Validator\Constraints\Code 不能放在属性或 getter 上

<?php
// vendor/app/mybundle/Validator/Constraints/Code.php

namespace App\Bundle\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;


class Code extends Constraint
{
public $message = 'Error validate message!!!';
public function validatedBy()
{
return 'alias_name';
}

public function getTargets()
{
//return self::CLASS_CONSTRAINT; // error "The constraint cannot be put on properties or getters"
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT); // working, but $value is a STRING!!!
}
}

我的 vendor/app/mybundle/Validator/Constraints/CodeValidator.php

<?php
// vendor/app/mybundle/Validator/Constraints/CodeValidator.php

namespace App\Bundle\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CodeValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$value->getId(); // this code not working, because $value is STRING!!
$this->context->buildViolation($constraint->message)
->atPath('code')
->addViolation();
}

我哪里做错了?

最佳答案

尝试将此添加到您的约束中:

/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*/

编辑

今天早上,我花时间在全新安装的 symfony 3 上尝试了您的实现。

此外,如果您在属性上添加 @AcmeAssert\Code,如下所示:

use AppBundle\Validator\Constraints as AcmeAssert;

// ...

/**
* @var string
* @AcmeAssert\Code
* @ORM\Column(name="code", type="string")
*/
private $code;

只有字段会被验证,所以$value代表属性的字段值。
例如,如果您在实体的 $code 属性上分配 @AcmeAssert\Code,则在提交表单时,$value您的验证器将代表您的 $code 属性的字段值)。

如果您在实体顶部添加 @AcmeAssert\Code,如下所示:

use AppBundle\Validator\Constraints as AcmeAssert;

/**
* Foo
*
* @ORM\Table(name="foo")
* @AcmeAssert\Code
* @ORM\Entity(repositoryClass="AppBundle\Repository\FooRepository")
*/
class Foo

然后,$value 将代表您的完整实体,您可以使用 getter 进行所需的所有验证。

我已经在存储库中添加了我的测试项目,您可以使用它来查看如何使用两个替代方案:sf3-constraint-test

在我的示例中,实体 AppBundle::Bar 对属性有约束,而 AppBundle::Foo 对整个实体有约束。

希望这是您所需要的!

EDIT2

如果您在 yaml 映射中,请使用以下内容将约束应用于您的整个实体并通过约束中的 $value 访问完整对象:

AppBundle\Entity\AcmeEntity:
constraints:
- App\Bundle\MyBundle\Validator\Constraints\Code: ~

在您的映射之上。

如果你只想在一个属性上应用约束,并使用 $value 访问字段的值,请保持原样并在 $value 上执行你的逻辑> 这是一个字符串(对应于映射中约束的实体属性的字段的值),它类似于:

AppBundle\Entity\AcmeEntity:
properties:
# ...
code:
- App\Bundle\MyBundle\Validator\Constraints\Code: ~

关于php - 不能对属性或 getter 施加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35163720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com