where put slugify method for symfony2 entities

2019-07-10 10:52发布

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);
}

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.

so what should i do? if use helper class I cannot use slugify() like upper method :-(.

4条回答
Luminary・发光体
2楼-- · 2019-07-10 11:17

For a quick fix you can create some sort of %Bundle%/Utils/Utils.php class (which can be static), put the function in there and use it like

use MyBundle/Utils/Utils;

class Someclass {
// ...
$this->slugTitle = Utils::slugify($t);

A more sophisticated approach would be using Gedmo's Doctrine Extensions. It handles that behaviour for you.

查看更多
一夜七次
3楼-- · 2019-07-10 11:23

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...
    }
}

services.xml:

<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.

查看更多
趁早两清
4楼-- · 2019-07-10 11:41

There is a package that you can you to do this for you.

It is called Sluggable behavior extension for Doctrine 2

查看更多
戒情不戒烟
5楼-- · 2019-07-10 11:44

Why not create a base class with your slugify function in (infact the whole setTitle could be in the base class if all your children have a title and needs slugging) and then inherit from it for all your entity classes?

class slugclass{

  $title
  $slugtitle

  public function setTitle($t){
      $this->title = $t;
      $this->slugTitle = $this->slugify($t);
  }

  public function slugify($t){
     ...sluggify code
  }

}


class childentity extends slugclass{

}
查看更多
登录 后发表回答