我有 slugify 方法,每次更改实体类的标题属性时都会对其进行 slugify 处理。 所以我把这个方法放在实体类中并这样调用:
public function setTitle($t){
$this->title = $t;
$this->slugTitle = $this->slugify($t);
}
它对我来说工作得很好,但是如果我有多个类使用 slugify 方法,我应该把这个方法放在所有的类中,这就是代码重复。
那我该怎么办呢?如果使用辅助类,我不能像上面的方法一样使用 slugify() :-(。
最佳答案
您可以使用 Doctrine event listener/subscriber监听实体的变化并采取行动。
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...
}
}
services.xml:
<service id="my.listener" class="Acme\DemoBundle\EventListener\SlugifyListener">
<tag name="doctrine.event_listener" event="preUpdate" />
</service>
但是在这种情况下,您最好查看 Doctrine Extensions bundle 。它提供了一个 Sluggable 扩展,可以为您完成此操作,而不是重新发明轮子。
关于php - symfony2实体的slugify方法在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27442048/