Jonwd
Jonwd

Reputation: 655

Event handling with simple dependency injection and decoupling

I'm developing a MVC framework for educational purposes. Now I'm stuck with how should I handle events in my framework.

The closest answer I was looking for was Adding events to an interface / implementation but it doesn't say anything about the injection part.

My question is, are both approaches good enough? are they decoupled?

The language is PHP but treat it as pseudo-code.

This first example is kind of C# approach. ClassA is injected with Kernel class, and it is its own responsibility to subscribe to the event.

class Kernel{
    public $onInit      = new EventHandler();
    public $onTerminate = new EventHandler();
    public function __construct(){
    }
    public function boot(){
        //...dosomething
        $this->onInit->raise($this, new EventArgs());
        $this->onTerminate->raise($this, new EventArgs());
    }
}
class ClassA{
    public function __construct($kernel){
        $kernel->onInit->add(array($this,'onKernelInit'));
    }
    public function onKernelInit($sender, $args){
        $this->doSomething($sender);
    }
    public function doSomething(Kernel $kernel){}
}

With this second approach, there is an intermediate class which is responsible for subscribing to the event. ClassAListener is injected with ClassA and KernelEventDispatcher.

class Kernel{
  public $dispatcher;
  public function __construct(KernelEventDispatcher $dispatcher){
    $this->dispatcher = $dispatcher;
  }
  public function boot(){
    //do something...
    $this->dispatcher->raiseInit($this, new EventArgs());
    $this->dispatcher->raiseTerminate($this, new EventArgs());
  }
}
class ClassAListener{
  public function __construct(ClassA $classA, KernelEventDispatcher $dispatcher){
    $this->classA = $classA;
    $dispatcher->onInit(array($this, 'onKernelInit'));
  }
  public function onKernelInit($sender, $args){
    $classA->doSomething($sender);
  }
}

I'm leaning towards the second approach as it is much cleaner, but I'm not sure if it is 'going the right way' (handling events).

Any help is appreciated.

Upvotes: 1

Views: 240

Answers (1)

Orangepill
Orangepill

Reputation: 24645

I believe that the second approach is better because the first approach creates a dependency on an implementation of EventHandler that is not immediately obvious and that would be difficult to extend or replace.

Upvotes: 1

Related Questions