PHP 组件注册的例子
1 <?php 2 namespace Test; 3 4 abstract class Plugin 5 { 6 protected $pluginName = null; 7 8 abstract public function action(); 9 10 function toString() 11 { 12 return $this->pluginName; 13 } 14 } 15 16 class HandPlugin extends Plugin 17 { 18 protected $pluginName ; 19 20 function __construct($name = 'Hand') 21 { 22 $this->pluginName = $name; 23 } 24 25 public function action() 26 { 27 // TODO: Implement action() method. 28 echo 'Raise your hand!' ."\n"; 29 } 30 } 31 32 class FootPlugin extends Plugin 33 { 34 protected $pluginName ; 35 36 function __construct($name = 'Foot') 37 { 38 $this->pluginName = $name; 39 } 40 41 public function action() 42 { 43 // TODO: Implement action() method. 44 echo 'Put down your foot!' ."\n"; 45 } 46 } 47 48 49 class People 50 { 51 protected $bodyPlugin = array(); 52 protected $giveName = null; 53 54 public function __construct($name ='Fully Man') 55 { 56 $this->giveName = $name; 57 } 58 59 public function register(Plugin $plugin) 60 { 61 if(!isset($this->bodyPlugin[$plugin->toString()])) 62 { 63 $this->bodyPlugin[$plugin->toString()] = $plugin; 64 } 65 else 66 { 67 return true; 68 } 69 } 70 71 public function unRegister(Plugin $plugin) 72 { 73 if(isset($this->bodyPlugin[$plugin->toString()])) 74 { 75 unset($this->bodyPlugin[$plugin->toString()]); 76 } 77 return true; 78 } 79 80 public function doBodyAction() 81 { 82 if(empty($this->bodyPlugin)) 83 { 84 echo 'Nothing to show!' ."\n"; 85 return false; 86 } 87 88 echo $this->giveName. " will do :\n"; 89 foreach($this->bodyPlugin as $name => $plugin) 90 { 91 echo $name. ": " ; 92 echo $plugin->action(); 93 } 94 } 95 } 96 97 $handPlugin = new HandPlugin(); 98 $footPlugin = new FootPlugin(); 99 $people = new People(); 100 101 $people->register($handPlugin); 102 $people->register($footPlugin); 103 104 $people->doBodyAction();
学习记录,方便复习