Jump to content

Chain of responsibility


aschk

Recommended Posts

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

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();
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.