Original: 8705313 Event-driven PHP event-driven programming--------------------------------------------------------------------------PHP: (http ://hi.baidu.com/yiqing95)
*
Event-driven is very common in desktop applications, such as when you click a mouse, click on a button application to respond to your actions, from the programmer's point of view, there are two characters need to identify: a user you are the system you build, but also no it! Now look at the behavior of the two in the middle of the pattern: the user is always sending a message to the system, this information prompted the system to respond, all requests from a more abstract perspective, there is no difference between: command and request; Please make a strict distinction between them, the command is to induce the system to make some changes (such as deleting a record), The request is that the system returns some information (such as a query), and of course the command usually feeds back some information to tell the system whether it was successful or failed, or an unpredictable exception occurred. From here, you can get a programming interface that adapts to all situations.
Execute (in paraminformation): returnedinformation; Parameters and return values are sometimes optional
The event model is the implementation of the "change-response" mechanism, a mechanism that can always be implemented by multiple methods, depending on how the programmer thinks about the problem. Inside PHP There is no concept of events, event dispatcher, but it doesn't mean that we can't use the event model to handle problems in the PHP world!!
*
**
Understanding Events:
What is the event, from your receptive point of view is the keyboard, mouse and other character movements caused by changes, this change is called the event: mouse click events, mouse drag events, keyboard click events .... From the perspective of our human perception of the world: all changes to you, or to everyone, are events, such as 918 events, 1212 event 911 events, and there is a change in nature without a moment, and only if these changes cause you enough attention, he is the event, For example, you can say that a major event happened in 1980---that day I was born (which is certainly a major event for your parents, at least more than 911); So finally, make a point: The event is a change, and any change can be defined as an event, so what happens when you decide.
From a computer perspective, all 01 sequence bit changes can be defined as events, still depends on you, but the most basic implementation of the computer is not read and write, so read and write the nature of the operation results (or this occurs) can be called events. There is a more special change is the time, from the four dimensions of space, although some things have not changed, but the time dimension is always moving forward, all the time can also cause events.
Any change or condition can be defined as an event, and if no information is exchanged, a closed system will not produce meaningful events for the outside world, if you only design a computer without a keyboard and mouse, it is estimated that the computer is at best a complex TV or DVD. Some interfaces are exposed externally to this program, and we are able to trigger certain changes through these interfaces. These interfaces can be either visual interfaces on the GUI or interface to the command line, and, of course, smaller components (subsystems, classes) from a copy-recursive perspective. ) exposes some APIs to the outside world.
An externally exposed interface is a pin to the inside of the system and a fuse that triggers the internal events of the system, and in web development these interfaces, such as hyperlinks, buttons, input boxes, drop-down menus, and so on, can trigger the system to respond to them. From the above event understanding, the event can be ignored (for example, 911 for others is the event for me is not, do not affect me), and the important point is that the event can be spread!! Changes can result in changes, so one event can lead to another. These are the characteristics of the event. What's worth mentioning? What happens if a circular event is formed to propagate the path??
**
***
We are the designers of the system, from a system point of view we need to respond to user requests and commands for the system. That is, you need to respond to some events and then do some processing to return the final execution or requested information to the customer. At the boundary of the system we need to map these events to the predefined response modules within the system:
Switch ($_get[' action ']) {
Case "Edit_record":
Edit_record ();
Break
Case "View_record":
View_record ();
Break
}
The above code is typical of how to handle an edit and query request sent over by the user via the HTTP GET method. Here we are in response to the user's hyperlinks or button events, (or possibly JS-triggered Ajax calls).
Note that the processing of these system boundaries is always very repetitive, and we have to constantly increase the complexity of these mappings when the system is growing, and we are violating dry (don ' t repeat yourself do not repeat yourself);
In the field of OOP, there is a fairly mature model for event-driven, and one of the purposes of design patterns is to not reinvent the wheel, so you can use it directly. There are two roles in the above functional event-handling contour, one is the event dispatcher (which is played by the Swith statement), and the other is the event responder (which is assumed by those two functions) and the other is the thing behind the case.
Look at this Url:http://myserver/interface.php?event=edit this URL clearly indicates the user's intention, to the system to respond to the edit event, in fact, there are many open source project URL design has a lot of this idea, such as act , the AC prefix means that the command/event backend will look for the corresponding processing script, and you can see something by carefully observing the law of the URL in Hong Sing's project. So the design can actually start from the URL, the URL is the interface, this in the object-oriented can be considered interface-oriented programming: For example, you want to edit the information of a book, you can first design the URL, such as:myserver/book.php?act=edit& bid=334455, if you want to view the information of a book, you can myserver/book.php?act=detail&bid=334455. And so on, this can also be considered a URL-driven design.
The responsibility of the event dispatcher is to query the event responder based on the event and pass the process to the event responder, who does not do the event handling itself.
All of the event responders are doing something similar: extracting the user's request parameters from $_get,$_post (or $_request) and doing something (file system, network, or database related work) and then returning the processing results. One of the most important features of OO is inheritance, which can bring the benefits of code reuse: by extracting public things into the parent class, subclasses only implement their own functions, so that you do not have to copy the code constantly, and it conforms to the dry principle.
Look at the whole life of the event: the user Action causes event ———— events to be passed from the network to the inside of the system ———— event is captured by the event dispatcher ———— the event dispatcher queries the processor ———— of the event the event dispatcher passes the process to the responding Event responder ———— Event Responder handles the event ———— "returns the processing result.
The above process is normal flow, of course there may be no registered event handler or exception condition. The above event is just a string (the information of course events is in post get and cookie).
***
****
Event Frame diagram:
The above diagram abstract class does not draw Getpdo method, there are parameter problems, you do it, you can not do it anyway PHP parameter information in the global array is placed, global array ($_get,$_post,$_cookie,$_request,$_server,$_ The session is the entire application of the communication bus);
The event dispatcher needs to have the ability to register and unregister event handlers. All event handlers implement the same interface, in order to facilitate the introduction of an abstract class in the middle, the class has a PDO attribute, which is a subclass common, but the handle method also needs to be instantiated (implemented by the specific class).
The purpose of this design is to standardize the code, PHP is a weak type of language, as long as you implement a method, you can think you are an implementation of an interface, this requirement is relatively broad, but for the sake of strict, or declare that they implement an interface, the registration will often also type check!.
The class is elaborate:
Class Dispatcher
{
Private $event;
function __construct ($EVENTSTR) {
$this->event = $eventStr;
}
function Handleevent () {
$eventReactorClass = "{$this->event}_handler";
if (class_exists ($eventReactorClass)) {
$handler _obj = new $eventReactorClass ($this->event);
$response = $handler _obj->handle ();
return $response;
}else{
echo "I can ' t handle this!";
}
}
}
The above code is mainly based on the string representing the event to find the corresponding event response class, and instantiate an event handler object, and then call its method handle, return the result of processing. There are many strategies can be used such as registering the event string with the mapping of the class, the event handler class is located in the folder, etc. can be considered, of course, "formula better than Configuration" has been accepted by many projects, so all the event responder class with the event name suffix _handler end, convenient development. So now the popular MVC framework has a set of naming conventions.
To extend the functionality of the system, you only need to implement the handle function of the event handler, and the class name contains information about which event to process. As for the parameters passed by the function, they can be optionally used or ignored. Of course, the general event dispatcher passes the most complete information as a parameter to the event responder. Custom request response classes are often passed as parameters, and request encapsulates $_get,$_post,$_cookie or $_request arrays. Response is generally cached as a collection container for response data.
Ieventhandle Interface class:
Interface Ieventhandle {
function handle ();
}
Provide a communication protocol so that all subclasses obey this protocol (that is, implement the handle method).
Abstract class EventHandler:
Abstract class EventHandler
{
Private $pdo;
function Getpdo () {
$this->pdo = new PDO (' config string ');
return $pdo;
}
abstract function handle ();
}
The main sub-class provides a convenient way to get PDO or database connection handle function, so that you do not have to repeat in the subclass to get the database connection code.
Of course, you can add public resources to this abstract class at will, depending on your project needs. The implementation of the specific event handler is deferred to the subclass.
Specific Event Responder classes:
Class Delete_handler extends eventhandler{
Private $event;
function __construct ($event) {
$this->event = $event;
}
The following tasks are implemented in this class: parameters see what happens.
function handle (...) {
$targetId = $_request[' id '];//get the deleted target ID
$pdo = Parent::getpdo ();
try{
Use PDO to complete the delete record operation
}catch (Pdoexception $ex) {
Throw $ex;
}
Or use template technology to display a page
return true;
}
}
****
*****
Introducing Security:
Whether a manipulation is allowed to execute requires reference to the current contextual information, and the context also refers to the environment, that is, which of the current actors is triggering the event;
The general implementation is this:
Performsomemethod () {
$operator = $_session[' user '];
if (!empty ($operator) && $operator = = ' Somerole ') {
Execute regular code here;
}eles{
echo "You are not authorized to do this!" ";
}
}
The above code is primarily programmed with validation logic to determine if a user is logged in, is a role, and then executes the normal execution logic if the logic is really what each event responder must do and then re-design a method called: Securehandle ()
Make it an abstract forced subclass implementation, and overwrite the dispatcher: Call this Securehandle () method instead, then the interface may also be changed, the interface in PHP may be just a convention, if the type is not checked then the interface seems dispensable. This kind of scenario is not very personal, so give me a plan that I think I can accept:
To rewrite an abstract class:
Abstract class EventHandler
{
Private $pdo;
function Getpdo () {
$this->pdo = new PDO (' config string ');
return $pdo;
}
Design patterns Using template methods
Public function handle ($eventContext) {
try{
If there are any parameters, pass them in.
$this->_before ($eventContext);
$response = $this->_handle ($eventContext);
$this->_after ($eventContext);
return $response;
}catch (Exception $ex) {
is the re-throw or how to handle it depends on your exception handling strategy
}
}
Protected Funciton _before (&$_context) {
This does not pass a validation failure by throwing an exception.
}
protected function _after (&$_context) {
Do whatever or log it here!
}
Forcing subclasses to implement this method
Abstract function _handle (&$_context);
}
After rewriting, the template method design pattern can be used to refer to the _before operation, and the _handle method is designed to implement the abstract forced subclass.
If the subclass also wants to change the security validation policy, it only needs to overwrite the _before action. So the original interface, event dispatcher, no need to change. In addition, the Before/after design mode is used here. Please find the relevant information yourself. Now the only thing the subclass has to do is to make a copy of the _handle method and, if necessary, the _before method.
*****
**************
Conclusion:
There are a lot of questions to consider, here are only a general idea, such as the GUI field often appear in the event registration mechanism is needed, mainly used to find the corresponding processor based on the event, of course, this mapping can be from the configuration file, or database. When combined with access control list technology, each user has a corresponding set of operational event handlers that can load all of its available event handler lists based on the current user ID, and then invoke the method of the appropriate processor, if the processor corresponding to the event is not found in the list to prove that the current user does not have this right. This logic can be extracted into an abstract class to implement.
Another problem to consider is the class loading problem, one of which is to include all of the class files that the system might use in advance, which is feasible in small projects, but is awkward for third-party libraries or for multiple folders and nesting with each other. Another approach is to read the mapping information from a configuration file about the file in which the class and class resides before the event dispatcher loads the class, and then include the class file in it. Another one is zendframework. Add the folder to the Classpath include_path then use the auto-load spl_autoload technique. I have a self-written in front of the automatic loading class can be used!
[Turn]php to implement event-driven