PHP design pattern series-Command)

Source: Internet
Author: User
PHP design pattern series-Command 1. Schema Definition

The Command mode encapsulates requests into objects, allowing you to parameterize customers with different requests, queue requests or record request logs, and support unrecoverable operations. This is very abstract. here is an example:

Assume that we have a caller class Invoker and a caller class that receives call requests. in this case, we use the execute method of the Command class Command to host the request call method, the caller Invoker only knows to call the execute method of the command class to process client requests, so as to decouple the Receiver and the caller Invoker.

The Artisan command in Laravel uses the command mode.

2. UML class diagram

3. sample code CommandInterface. php
 HelloCommand. php
  Output = $ console;}/*** run and output "Hello World" */public function execute () {// functions are fully implemented using the command class when there is no aggreger $ this-> output-> write ('Hello World ');}}
Receiver. php
  Invoker. php
   Command = $ cmd;}/*** run command */public function run () {$ this-> command-> execute ();}}
4. test code Tests/CommandTest. php
   Invoker = new Invoker (); $ this-> invoer = new invoer ();} public function testInvocation () {$ this-> invoker-> setCommand (new HelloCommand ($ this-> invoer); $ this-> expectOutputString ('Hello World '); $ this-> invoker-> run ();}}
5. Summary

The command mode abstracts similar behaviors of a group of objects, decouples callers from callers, and improves the flexibility of applications. The command mode encapsulates the heterogeneity of the called target object and provides services to the caller in a unified manner.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.