1

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?

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Stackster
  • 11
  • 1
  • This is a common misunderstanding of attributes - they don't proactively do anything, they are just metadata stored for you to access later. To make them do something, you have to have code that looks them up via reflection and decides what to do. – IMSoP Jun 16 '22 at 09:28
  • I see. So by using a reflection class I can look up the Attribute in the class containing the method with the attribute, and then do something with the data inserted in the parameter ($eventName and $method). But doesn't that still require an event to trigger the reflection logic? And if so, isn't it easier to just use a regular event, and not use attributes to define where it should be raised? – Stackster Jun 16 '22 at 09:49
  • Yes, you still need some code somewhere to actually despatch the events; the attributes are just a way of *configuring* that code. So if you currently have code that says `register_event('doSomething', MyEvent::class, ["somethingHappened", "POST"]);` you can replace that with code that looks through your source for relevant attributes and registers events when it finds one. That would generally run in a "build" script and save the configuration it found to a cache. – IMSoP Jun 16 '22 at 10:56

0 Answers0