Skip to content

[HttpKernel] Add before and after hooks to controller actions #57079

@tsantos84

Description

@tsantos84

Description

When we need to execute code before or after controllers, we need to:

  1. create a listener class and register the event listeners
  2. in the event listener, check if the incoming request is the master request
  3. check manually the route name or if the controller::action matches the expected names
  4. execute the business code

Creating such listener once is ease and works properly. But, the down side of this approach is that we don't have much clarity on what is being executed before or after controllers, mainly business code. (Framework code is ok).

The suggestion is to add two more attributes to the framework where we can declare what hooks will be executed before and/or after controller actions.

WDYT?

Example

The following example will trigger Stopwatch::__invoke service before/after all actions in this controller.

<?php

#[Before(Stopwatch::class, ["dev"])]
#[After(Stopwatch::class, ["dev"])]
class MyController {
    public function fooAction(): Response {
        return new Response('foo');
    }

    public function barAction(): Response {
        return new Response('foo');
    }
}

Or in case to add hooks to a specific controller action:

<?php

class MyController {

    #[Before(service: 'my_stop_watch_service', when: ["dev"])]
    #[After(service: 'my_stop_watch_service', when: ["dev"])]
    public function fooAction(): Response {
        return new Response('foo');
    }
}

This new feature suggestion is to controller actions but could be expanded to console commands as well.

This is not the case to change the request/command workflow. All of this can be done by the native event dispatcher.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureHttpKernelRFCRFC = Request For Comments (proposals about features that you want to be discussed)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions