Skip to content

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

@maxgalbu

Description

@maxgalbu

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:

let hasEventsManager = typeof eventsManager == "object";

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

Metadata

Metadata

Assignees

Labels

new feature requestPlanned Feature or New Feature Request
No fields configured for Feature.

Projects

Status
Released

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions