aschk Posted November 7, 2007 Share Posted November 7, 2007 See as the topic I was interested that mentioned chaining was "Solved" i thought i would start up the conversation/debate here. How do you guys use chaining (chain of responsibility)? The example I saw regarding the MySQL class seemed to involve doing the following : $class = new myclass(); $class->func1()->func2()->func3(); Each of those functions returns the $this reference to the myclass object thus allowing further calling of functions. I can see that this is clearly "chaining" of functions, but what benefit does this gain over $class = new myclass(); $class->func1(); $class->func2(); $class->func3(); Link to comment https://forums.phpfreaks.com/topic/76355-chain-of-responsibility/ Share on other sites More sharing options...
aschk Posted November 7, 2007 Author Share Posted November 7, 2007 Following on from my previous post I thought I should provide an example of how to implement chain of responsibility in PHP. <?php abstract class Logger { protected $next; public function setNext(Logger $logger){ $this->next = $logger; return $this; } abstract public function performCheck(); } class DBLogger extends Logger { private static $counter = 1; private $do; public function __construct($do){ if(is_bool($do)){ $this->do = $do; } else { $this->do = false; } } public function performCheck(){ if($this->do){ echo "Performing DB Check ".self::$counter."<br/>"; self::$counter++; } if(!is_null($this->next)){ $this->next->performCheck(); } } } class MailLogger extends Logger { private $do; public function __construct($do){ if(is_bool($do)){ $this->do = $do; } else { $this->do = false; } } public function performCheck(){ if($this->do){ echo "Performing Mail Check "."<br/>"; } if(!is_null($this->next)){ $this->next->performCheck(); } } } // Initialise our chain objects. $db1 = new DBLogger(false); $mail = new MailLogger(true); $db2 = new DBLogger(true); // Set up the chain. $db1->setNext($mail->setNext($db2)); // Do our function, let our chain handle it. $db1->performCheck(); ?> Link to comment https://forums.phpfreaks.com/topic/76355-chain-of-responsibility/#findComment-386597 Share on other sites More sharing options...
aschk Posted November 7, 2007 Author Share Posted November 7, 2007 One thing i've very aware of here is chaining the same method to itself causing an infinite loop. Anyone got a decent practical example of a c-o-r , seeing as mine is more of an example... Link to comment https://forums.phpfreaks.com/topic/76355-chain-of-responsibility/#findComment-386612 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.