How to use PHP Attributes as Events?

23 Views Asked by At

Lets say i have an attribute class:

#[Attribute(Attribute::TARGET_METHOD)]
class MyEvent
{
    /**
     * @phpstan-param null|Request::METHOD_* $method
     */
    public function __construct(
        public string $eventName,
        public ?string $method = null,
    ) {
       // do something in this constructor when event is raised...
    }
}

Then when I need to raise/dispatch the event I would add the attribute to the calling method like so:

    #[MyEvent("somethingHappened", "POST")]
    private function doSomething(): void
    {
        //does something
    }

Now, what i want to happen is:

  1. doSomething() gets called from somewhere
  2. constructor in MyEvent gets executed

But what actually happens? Nothing.

So my question: How could do so that the only thing necessary to raise my event, is to add the attribute to the method?

0

There are 0 best solutions below