Skip to content

Decorator pattern in open source code

Published: at 10:00 AM

In some open source repositories that contain a small number of maintainers are common to see classes as final, it happens because they can make modification without complex Backward Compatibility Promise, But on the other hand it keeps code a bit “complicated” to modify!

But well it is not so complicated since they implements interfaces and use composition in the code 😁, and here starts the beneficial of Decorator pattern 💅.

Table of contents

Open Table of contents

Open source code

I was looking for some project that has a good number of users, Then I choose EasyAdminBundle as example, it has more then +18k users and 4k starts

the piece of code that I gonna use is AdminUrlGenerator.php, and we gonna add a dispatch event when the generate method is called.

Creating a decorator

As the AdminUrlGenerator.php is a final class, it is not possible to extends this class and override generate method, and in this case an alternative is use a decorator.

<?php

declare(strict_types = 1);

namespace App\Decorator;

use App\Event\UrlGeneratedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGeneratorInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

#[AsDecorator(decorates: AdminUrlGenerator::class)]
class AdminUrlGeneratorDecorator implements AdminUrlGeneratorInterface
{
    public function __construct(
        #[AutowireDecorated]
        private AdminUrlGeneratorInterface $adminUrlGenerator,
        private EventDispatcherInterface $event,
    ) {
    }

    public function generateUrl(): string
    {
          $url = $this->adminUrlGenerator->generate();
          $this->event->dispatch(new UrlGeneratedEvent($url));

          return $url;
    }

    public function setRoute(string $routeName, array $routeParameters = []): self
    {
        $this->adminUrlGenerator->setRoute($routeName, $routeParameters);

        return $this;
    }

    public function get(string $paramName): mixed
    {
        return $this->adminUrlGenerator->get($paramName);
    }

    //....
}

Breaking Down AdminUrlGeneratorDecorator class

#[AsDecorator(decorates: AdminUrlGenerator::class)]

//...

#[AutowireDecorated]

As EasyAdminBundle is based on Symfony Freamework. it is one of the way to decorate a class.

in decorates parameter you pass the class that you want to decorate, this way Symfony will inject AdminUrlGeneratorDecorator instead of AdminUrlGenerator

and as we want reuse the original class, we are going to add #[AutowireDecorated] on top of $adminUrlGenerator. It will inject AdminUrlGenerator class on that parameter.

<?php

final class AdminUrlGeneratorDecorator implements AdminContextProvider

Here we are creating the decorator and implementing the same interface used in AdminUrlGenerator class, it is important because this class is injected via __construct via AdminContextProvider interface, and as both class implements the same interface we can choose which class we want to in inject and in our case we gonna inject the new class created (AdminUrlGeneratorDecorator)

<?php

    public function __construct(
      #[AutowireDecorated]
      private AdminUrlGenerator $adminUrlGenerator,
      private EventDispatcherInterface $event,
    ) {
    }
<?php
    public function generateUrl(): string
    {
          $url = $this->adminUrlGenerator->generate();
          $this->event->dispatch(new UrlGeneratedEvent($url));

          return $url;
    }

It is the method that we want to modify, on the first line we are calling the original method to generate the url. the second line is dispatching our event and in the last one we are returning the url generated by original method.

<?php
    public function setRoute(string $routeName, array $routeParameters = []): self
    {
        $this->adminUrlGenerator->setRoute($routeName, $routeParameters);

        return $this;
    }

    public function get(string $paramName): mixed
    {
        return $this->adminUrlGenerator->get($paramName);
    }

    //....

Maybe you were asking yourself, “why do I need those methods if I just want to change generate method?”

It is needed because AdminContextProvider is forcing to implement those methods. and this case we must implement them and call the original implementation, like I did with setRoute and get methods

Just to simplify the example I did not add all methods, But you must add all of them.

Full example

//src/Decorator/AdminUrlGeneratorDecorator.php
<?php

declare(strict_types = 1);

namespace App\Decorator;

use App\Event\UrlGeneratedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGeneratorInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

#[AsDecorator(decorates: AdminUrlGenerator::class)]
class AdminUrlGeneratorDecorator implements AdminUrlGeneratorInterface
{
// ...
//src/Event/UrlGeneratedEvent.php
<?php

declare(strict_types=1);

namespace App\Event;

class UrlGeneratedEvent
{
    public function __construct(private string $url)
    {
    }

    public function getUrl(): string
    {
        return $this->url;
    }
}
//src/Listener/UrlGeneratedListener.php
<?php

declare(strict_types=1);

namespace App\Listener;

use App\Event\UrlGeneratedEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
class UrlGeneratedListener
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public function __invoke(UrlGeneratedEvent $event)
    {
        $this->logger->info(
            'New url generated.',
            [
                'url' => $event->getUrl(),
                'eventClass' => get_class($event),
                'listenerClass' => get_class($this),
            ]
        );
    }
}

AdminContextProvider interface is used in some classes as MenuFactory.php, this class is called when we load some admin page that contain menu!

Then when a call /admin page, you can see there is a info log created by our Listener. Image with symfony profile page on log section


Next Post
How to easily setup PHP on your machine