Home > Enterprise >  Is it possible to use the Slugger interface other than in a constructor?
Is it possible to use the Slugger interface other than in a constructor?

Time:11-29

I'm looking to use the sluggerInterface in a class. But I want to keep:

public function __construct()
    {
    }

So I want to use sluggerInterface in my class without adding any argument in my constructor. (this is in order to automatically create 1 slug when creating an object).

So I want a code different from this one:

use Symfony\Component\String\Slugger\SluggerInterface;

    class MyService
    {
        private $slugger;
    
        public function __construct(SluggerInterface $slugger)
        {
            $this->slugger = $slugger;
        }
    
        public function someMethod()
        {
            $slug = $this->slugger->slug('...');
        }
    }

Thank you !

CodePudding user response:

You do not want to use autowiring in your constructor ?

You could just create a new slugger, for example with Symfony\Component\String\Slugger\AsciiSlugger;

$slugger = new AsciiSlugger();
$slugger->slug('Please slug this.')->toString();

Or you could also use autowiring with another method using @required annotation (or attribute #[Required] for PHP 8 )

private $slugger;

#[Required]
public function setSlugger(SluggerInterface $slugger): void
{
    $this->slugger= $slugger;
}

this is in order to automatically create 1 slug when creating an object

You may also want to look into event listener, using doctrine event prePersist to slug your entity when persisted could be another idea.

Finally, gedmo doctrine-extensions sluggable may interest you as well.

  • Related