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. SummaryThe 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.