cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[NFR]: Allow setting dispatcher events manager during controller initialize()

Open maxgalbu opened this issue 2 years ago • 0 comments

Is your feature request related to a problem? Please describe. I have an external phalcon library that I need to use in multiple projects to set additional headers in a specific condition. It needs to listen to the event dispatch:afterExecuteRoute, after which the library sets the additional headers and that's it. Eg inside the controller where i want to add headers, I do this:

public function initialize() {
    $this->attachPhalconTraceHeaderSetter();
}

and in the trait used, I do this:

private bool $attached_phalcon_trace_header_setter = false;

protected function attachPhalconTraceHeaderSetter(): void {
    if (!$this->attached_phalcon_trace_header_setter) {
        $this->attached_phalcon_trace_header_setter = true;

        /** @var Dispatcher $dispatcher */
        $dispatcher = $this->getDI()->getShared("dispatcher");
        $eventsManager = $dispatcher->getEventsManager();
        if ($eventsManager) {
            $eventsManager->attach("dispatch:afterExecuteRoute", function (Event $event, Dispatcher $dispatcher) {
                //set headers on $this->response
            });
         }
    }
}

The issue is that if there's a default dispatcher (like 99% of the projects i'm working on), there's no events manager in the dispatcher and setting an events manager in the controller initialize() doesn't trigger any event because of this: https://github.com/phalcon/cphalcon/blob/485ad1a0f1814e4cb634c23069ca851d3b533fe2/phalcon/Dispatcher/AbstractDispatcher.zep#L193

Describe the solution you'd like Allow setting an events manager in the controller initialize()

Describe alternatives you've considered Setting an emtpy events manager on each of the projects my team on + document that the library user should add a dispatcher WITH events manager + remember to set it in every new project

maxgalbu avatar Sep 26 '23 15:09 maxgalbu