andres-montanez / Magallanes

The PHP Deployment Tool
https://magephp.com
MIT License
694 stars 167 forks source link

Event subscribers #420

Closed Toflar closed 2 years ago

Toflar commented 6 years ago

There were already other issues about registering custom commands and I also submitted a PR for an ssh command which was declined and I have no possibility to add it on my own at the moment.

So I thought I'll come up with a simple concept that allows us to provide events for whatever extension point you may think of. The one that supports registering custom commands is just the first one but it serves as a useful example right away.

So subscribers are registered like so:

magephp:
    subscribers:
        - Vendor\MageExtension\SuperEventSubscriber

All that class has to do is to implement the Symfony EventSubscriberInterface and register to any event we will add in the future. The Runtime now has a getEventDispatcher() allowing to dispatch events everywhere within the application. You can do it in built-in tasks yourself or one can do it in custom tasks for whatever reason. This concept provides a lot of flexibility.

Using this concept, we can easily register a new command. So if I wanted to add my SSH command, my .mage.yml would look like so:

magephp:
    subscribers:
        - Vendor\MageExtension\SshCommandProviderEventSubscriber
class SshCommandProviderEventSubscriber implements EventSubscriberInterface
{
    public function registerCommands(RegisterCommandsEvent $event)
    {
        $event->addCommand(new SshCommand());
    }

    public static function getSubscribedEvents(): array
    {
        return [
            RegisterCommandsEvent::EVENT_NAME => ['registerCommands'],
        ];
    }
}

Then I can use vendor/bin/mage ssh 😄

No tests yet, I would like to know your thoughts about the concept!

coveralls commented 6 years ago

Coverage Status

Coverage decreased (-1.2%) to 98.778% when pulling 3ac452f1cb81206643f0157b3f4f6a0a15ec55fa on Toflar:event-subscribers into e30de6b719c923d70917a9f9364efdb29b7e9362 on andres-montanez:master.

andres-montanez commented 2 years ago

This is a bit overkill for the feature set of Mage.