Skip to content

URL Slug🔗

Allow you to convert entities titles or names into url friendly slugs using symfony/string.

For example:

Développeur Expert Back end Symfony 2 (H/F)

becomes:

developpeur-expert-back-end-symfony-2-h-f

Installation🔗

1
composer require symfony/string

Usage🔗

1
2
$slugger = new AsciiSlugger();
$slug = $slugger->slug($title);

Note: See documentation for extra configuration.

Interface and implementation🔗

The interface to add in your src/Domain or src/Application depending where you need to generate slugs:

1
2
3
4
interface SlugGeneratorInterface
{
    public function generate(string $text): string;
}

The implementation to add in your src/Infra:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class SlugGenerator implements SlugGeneratorInterface
{
    private SluggerInterface $slugger;

    public function __construct(SluggerInterface $slugger)
    {
        $this->slugger = $slugger;
    }

    public function generate(string $text): string
    {
        $slug = $this->slugger->slug($text);

        if ($slug->isEmpty()) {
            throw new \RuntimeException('Empty slug.');
        }

        return $slug->lower()->toString();
    }
}

Last update: December 20, 2024