Symfony2:是否可以在接口上放置验证注释?
假设我有接口:
namespace Acme\Bundle\FooBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
interface IFoo {
/**
* @Assert\NotBlank
* @Assert\MaxLength(3000)
*/
function getBody();
}
两个类实现该接口,并且我希望这些类也能够使用 getBody
声明上的验证注释。 (即我不想在每个实现 IFoo 的子类中重复验证代码,因为它违反了 DRY)。
然而,这样做给了我以下例外:
尝试调用抽象方法 Acme\Bundle\FooBundle\Entity\IFoo::getBody()
有谁知道这是否可能或有任何解决方法?
Say I have the interface:
namespace Acme\Bundle\FooBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
interface IFoo {
/**
* @Assert\NotBlank
* @Assert\MaxLength(3000)
*/
function getBody();
}
Two classes implement the interface and I want those classes to also be able to make use of the validation annotations on the getBody
declaration. (i.e. I don't want to have to duplicate the validation code in each subclass implementing IFoo
since it violates DRY).
Doing this however gives me the following exception:
Trying to invoke abstract method Acme\Bundle\FooBundle\Entity\IFoo::getBody()
Does anyone know if this is possible, or any workarounds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎你无法注释接口,github上有一个针对此问题的票证:
https: //github.com/symfony/symfony/issues/2841
Seems that you can't annotate an interface, there is a ticket open on github for this issue:
https://github.com/symfony/symfony/issues/2841
我认为您不能对方法声明使用验证,因为它们应该与属性一起使用。您可以使用抽象 映射超类不过,为此。
然后,类似“
您”的课程可以从该课程扩展您的其他课程。
I don't think you can use validation for method declarations as they are supposed to be used with properties. You could use an abstract mapped superclass for this, though.
Something along the lines of
You could then extend your other classes from this one.