Meaning of Event in php

后端 未结 2 632
渐次进展
渐次进展 2021-01-03 12:30

I know php and nodejs too,in javascript we have asynchronize programming ,so I understand meaning of event in it.but I saw Event in Yii and Zend 2 and use t

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-03 13:08

    First of all, there are no events in PHP

    An event is an abstraction for callback functions with their name. Typically, we'd define them as $eventName => $listener, where $listener is a callback function for the $eventName

    What is the difference between events and regular callback functions?

    Again - the core point to remember, is that events are callback functions. Nothing more.

    The only difference between them, is how we do invoke them.

    An event is defined on bootstrap step with its required arguments, but invoked on demand without arguments. While the callback function is invoked with arguments and only

    Consider this example,

    attach('my_event', function(){
    
       print_r(func_get_args());
    
    }, array('foo', 'bar'));
    

    As we have just defined an event, we'd invoke like,

    $eventManager->trigger('my_event');

    This will output: Array([0] => [foo], [1] => [bar]

    That's related to JavaScript!

    Since most of us are familiar with JavaScript even-driven architecture, its worth nothing to mention an example of its common usage:

    var a = document.getElementsByTagName('a')[0];
    a.onclick = function(event) { // <-- We define an event with the event argument
       event.preventDefault();
       alert('A element was clicked');
    }
    
    a.click(); // <-- but we invoke it without arguments
    
    // or If you want a Jquery
    $("a").click(function(event){
       event.preventDefault();
       alert('A element was clicked');
    });
    
    $("a").click();
    

    Since in PHP we don't have such event-driven nature, we can replace it with our own class that manage events and takes a full advantage of it.

    Why use them?

    While events confuse so many people, they are extremely useful.

    Imagine you have a Content Management System (CMS), where your users can decide how to handle 404 errors. Say, they can handle with

    1) Show a blank page
    2) Redirect to /
    3) Show a custom message

    Without events you would have to do it, like

    if ($router->isMatched($request)){
    
        //do dispatch etc
    
    } else {
    
       // Here you start handling 404 errors
    
       switch($config->read('404_way_handle')){
    
           case 'show_blank':
              die();
           break;
    
           case 'show_msg':
              echo 'Some custom message';
           break;
    
           case 'redirect':
              // do redirect
           break;
       }
    }
    

    With an event you can simplify the readability and keep the code more maintainable:

    if ($router->isMatched($request)){
       // do dispatch
    } else {
    
       $eventManager->trigger('404_handler');
    }
    

    while 404_handler itself looks like

      $eventManager->attach('404_handler', function(){
    
           switch($config->read('404_way_handle')){
    
               case 'show_blank':
                  die();
               break;
    
               case 'show_msg':
                  echo 'Some custom message';
               break;
    
               case 'redirect':
                  // do redirect
               break;
           }
    
      }, $config);
    


    So let's break it down

    1) Events improve readability, which is great for future

    2) Events do adhere to the Single-Responsibility Principle, because you can simply inject $eventManager to your classes that need it, while callback functions could break it or could introduce a global state too (Which is bad for unit-testings).

    3) There are distinct types of logic - template logic, business logic, error handler logic, data access logic etc etc. Events do simplify your application logic by decoupling business (or another kind) logic from its configuration logic, so that you end up with clear application logic.

    You can watch this lecture if you want to know how they do work in Zend Framework 2 (watch it even if you're not familiar with Zend Framework 2)

    Events in MVC-related architectures

    Since you've been talking about frameworks, its worth nothing to mention, that there could be events in MVC-related architectures too. And since events are callback functions you can abstract common boostrap events in your MVC-like architecture, like this.

    $mvcEvent->on(MVC_EVENT::ROUTE_MATCH, function(){
    
      $mvcEvent->on(MVC_EVENT::DISTPATCH, function($content){
    
        echo $mvcEvent->trigger(MVC_EVENT::RENDER, $content);
    
      });
    
    });
    

    Note : In pure MVC theory, there are no events at all. They do acts as helpers, but again - in frameworks you can abstract them and call them "events".

提交回复
热议问题