PhileCMS / Phile

A flat file CMS with a swappable parser and template engine.
https://philecms.github.io/
Other
257 stars 49 forks source link

reduce plugin event boilerplate #199

Closed Schlaefer closed 9 years ago

Schlaefer commented 9 years ago

From what I've read many Pico users find Phile harder to grok. Namespaces, events etc. are difficult concepts for non-devs.

So I tried to revise the demo plugin to make it more accessible:

Event initialization is now possible by simply defining a protected $events = ['<event>' => '<method>'] as Plugin class property. No more __constructor() and on() with if trees.

So a basic Plugin class is now:

namespace Phile\Plugin\Mycompany\Myplugin;

class Plugin extends \Phile\Plugin\AbstractPlugin {

    protected $events = ['before_parse_content' => 'doSomething'];

    public function doSomething($data = null) {
        // …
    }
}

Best part: it's completely backwards-compatible. No need to touch your code if you're lazy or prefer the verbose way. Nonetheless I changed the core plugins to use $events.

STOWouters commented 9 years ago

+1 I like this implementation more than the old one. It's more direct than calling on and check which one of the event is called.

james2doyle commented 9 years ago

This looks very clean. Nice work!

I can't think of a case personally, but user could still leverage the __construct if they needed to right? I guess the alternative would be to use the plugins_loaded event.

Schlaefer commented 9 years ago

but user could still leverage the __construct if they needed to right

The constructor is completely unused and we don't assume anything about it. You are free to use it as you like. Nothing changes in that regard.

The event initialization of $events happens in a function call that appears after the construction of the Plugin class. See this commit. Prior AbstractPlugin::injectSettings() only initialized the $settings property, now AbstractPlugin::initialize bootstraps the $settings and $events (if set).

If you don't like the $events sugar you can completely ignore it and still use the exact same __construct() and on() systematic to set up events manually, hence the backwards-compatibility.