问题描述
我有一个slugify方法,每次更改实体类的标题属性。
所以我把这个方法放在实体类中并调用它:
I have slugify method that slugify title attribute of entity class every time it change.so I put this method in entity class and call it like this:
public function setTitle($t){
$this->title = $t;
$this->slugTitle = $this->slugify($t);
}
它对我来说很好,但如果我有多个使用slugify方法的类我应该将这个方法放在所有的方法中,这是代码重复。
it work fine for me, but if I have more than one class that use slugify method I should put this method in all of them, and this is code duplication.
那么我该怎么办?如果使用helper类,我不能像上面的方法那样使用slugify(): - (。
so what should i do? if use helper class I cannot use slugify() like upper method :-(.
推荐答案
你可以使用听取实体更改并对其执行操作。
You can use a Doctrine event listener/subscriber to listen to entity changes and act on them.
namespace Acme\DemoBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
class SlugifyListener
{
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
// do something with $entity...
}
}
:
<service id="my.listener" class="Acme\DemoBundle\EventListener\SlugifyListener">
<tag name="doctrine.event_listener" event="preUpdate" />
</service>
然而,在这种情况下,更好地了解。它提供了一个可伸缩的延伸,可以为您做这个,而不是重新发明轮。
However in this case, you're better off taking a look at the Doctrine Extensions bundle. It provides a Sluggable extension which can do this for you, rather than reinventing the wheel.
这篇关于哪里可以使用symfony2实体的slugify方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!