事件的意义在php [英] Meaning of Event in php

查看:106
本文介绍了事件的意义在php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也知道php和nodejs,在javascript中我们有异步编程,所以我明白事件的意思,但是我在Yii和Zend 2中看到事件,也可以使用它们,但是我可以不了解其意义,它在PHP中的工作原理以及其中的功能?

解决方案

首先,在PHP中没有任何事件



事件是具有名称的回调函数的抽象。
通常,我们将它们定义为 $ eventName => $ listener ,其中 $ listener $ eventName



事件和常规回调函数之间有什么区别?



再次 - 要记住的核心要点是事件是回调函数。没有更多的。



它们之间的唯一区别是我们如何调用它们。



事件在引导步骤中使用其所需的参数进行定义,但按需调用无参数。虽然使用参数调用回调函数,但只有



考虑这个例子,

 <?php 

$ eventManager = new EventManager();
$ eventManager-> attach('my_event',function(){

print_r(func_get_args());

},array('foo' '酒吧'));

正如我们刚刚定义的一个事件一样,我们会像b

$ eventManager-> trigger('my_event');



输出: Array([0] => [foo],[1] => [bar]



这与JavaScript有关!



由于我们大多数人都熟悉JavaScript甚至驱动的架构,所以它的价值一点都不用说它的常见用法:

  var a = document.getElementsByTagName('a')[0]; 
a.onclick = function(event){// < - 我们定义一个事件与事件参数
event.preventDefault();
alert('A元素被点击');
}

a .click(); //< - 但是我们调用它没有参数

//或者如果你想要一个Jquery
$(a)点击(function(event) {
event.preventDefault();
alert('A element was clicked');
});

$(a)click() ;

自PHP开始我们没有这样的事件驱动的性质,我们可以用我们自己的类来替代它来管理事件,并充分利用它。



为什么要使用它们? / h2>

虽然事件混淆了这么多人,他们是非常有用的。



想像你有一个内容管理系统(CMS),您的用户可以决定如何处理 404 错误。说,他们可以用



处理1)显示一个空白页

2)重定向到 /

3)显示自定义消息



没有事件,你必须这样做,

  if($ router-> isMatched($ request)){

//做调度etc

} else {

//这里开始处理404错误

switch($ config-> read('404_way_handle')) {

case'show_blank':
die();
break;

case'show_msg':
echo'一些自定义消息';
break;

case'redirect':
// do redirect
break;
}
}

有了一个事件,你可以简化可读性,并保持代码更可维护:

  if($ router-> isMatched($ request)){
//做调度
} else {

$ eventManager-> trigger('404_handler');
}

404_handler 本身看起来像

  $ eventManager-> attach('404_handler',function(){

开关($ config-> read('404_way_handle')){

case'show_blank':
die();
break;

case 'show_msg':
echo'一些自定义消息';
break;

case'redirect':
// do redirect
break;
}

},$ config);




分解它



1)事件提高可读性,这对未来很好



2)事件遵守单一责任原则,因为您可以简单地将 $ eventManager 注入到需要它的类中,而回调函数可能会破坏它或者可能会引入全局状态(这对于单元测试是不利的)。



3)有不同类型的逻辑 - 模板逻辑,业务逻辑,错误处理程序逻辑,数据访问逻辑等。事件通过将业务(或另一种)逻辑与其配置逻辑分离来简化应用程序逻辑,以便你最终得到了明确的应用逻辑。



你可以看这个讲座如果你想知道如何他们在Zend Framework 2中工作(即使您不熟悉Zend Framework 2)也可以工作。



MVC相关体系结构中的事件



由于您一直在谈论框架,它的价值不言而喻,也可能在 MVC相关的体系结构中发生事件。而且由于事件是回调函数,您可以像这样在MVC类架构中抽象常见的 boostrap 事件。



<$ p (MVC_EVENT :: ROUTE_MATCH,function(){

$ mvcEvent-> on(MVC_EVENT :: DISTPATCH,function($ content) {

echo $ mvcEvent-> trigger(MVC_EVENT :: RENDER,$ content);

});

});

注意:在纯MVC理论中,根本没有事件。他们作为助手,但是再次 - 在框架中,您可以抽象他们并称之为事件。


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 them too,but I can't understand the meaning of it,how it works in php and what exactly does in it?

解决方案

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,

<?php

$eventManager = new EventManager();
$eventManager->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".

这篇关于事件的意义在php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆