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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.