donglu3243 2017-02-28 18:28
浏览 100
已采纳

了解PHP事件调度系统

I've never done anything event-driven in PHP, only Node.js, so I'm trying to understand how event dispatching systems work in PHP (such as Laravel events, CakePHP events and Symfony event dispatcher).

This example is in the Laravel docs:

protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

Since the lifetime of a PHP script running on Apache is basically the lifetime of the request, does this mean all the event listeners are instantiated with each request?

So if I have 120 listeners in my application (i.e. listed in this $listen property), are all 120 of them going to be instantiated every time a page is visited? Or do the listener objects only get instantiated when the appropriate events are dispatched?

It seems quite inefficient for the listeners to be instantiated with each request when in the entire duration of the request there might not even be a single event fired.

Is this something that I should even be concerned about?

  • 写回答

1条回答 默认 最新

  • douwo1517 2017-02-28 18:57
    关注

    How an Event Listener system works.

    In simplest terms it's just an array of text objects.

    So in symfony you might do something like this

    $eventManager->dispatch('my_cool_event_name', $eventPayload);
    

    This will then look for anything that is listening for the event my_cool_event_name by just doing an array look up

    $events = [
        'my_cool_event_name' => [
            'events
    otifyController::email',
            'events
    otifyController::text',
            'events
    otifyController::tweet',
        ],
        'another_event' => [
    
        ]
    ];
    

    So from the array example above it found 3 events listening on my_cool_event_name, it'll then instansiate events otifyController and run the methods passing through the $eventPayload to each event.

    If you never dispatched my_cool_event_name during execution then nothing gets instansiated

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部