HomePHP Page 3 - Introducing Bridge Classes with PHP 5
Implementing the bridge pattern’s core logic - PHP
The bridge class, or what's commonly known as the bridge pattern, lets you create a class with its abstract functionality and implementation residing on different class hierarchies. This lets you decouple the class from its concrete application. This article, the first of three parts, introduces you to the bridge pattern and its uses.
In consonance with the intrinsic definition of the bridge pattern, it should be possible to separate a given class from its concrete implementation (without using abstract classes at all), since both of them will reside on different class hierarchies. This concept will be much easier to grasp if you take a look at the signature of the following bridge class, which takes up objects of type “Message” and saves them to different locations.
That being said, the definition for this brand new class is as follows:
// define class 'BridgeObjectSaver'
class BridgeObjectSaver{
private $messageObj;
private $objSaver;
public function __construct(Message $messageObj,$saveCommand){
if(!in_array($saveCommand,array('array',
'file','cookie'))){
throw new Exception('Invalid save command');
}
$this->messageObj=$messageObj;
// target object is saved to array
if($saveCommand=='array'){
$this->objSaver=newObjectToArraySaver();
}
// target object is saved to file
elseif($saveCommand=='file'){
$this->objSaver=new ObjectToFileSaver();
}
// target object is saved to a cookie
else{
$this->objSaver=new ObjectToCookieSaver();
}
}
public function save(){
$this->objSaver->save($this->messageObj);
}
}
As shown above, this completely new “BridgeObjectSaver” class is capable of storing an object of type “Message” in different places, such as a plain text file, an array or a simple cookie. Nevertheless, I’d like you to study specifically how all these tasks are performed by the mentioned bridge class.
As you can see, there’s a third object involved in this process called “ObjectSaver.” This object actually carries out all the storage procedures that I discussed before. Obviously the “BridgeObjectSaver” class behaves like a real “bridge” for “ObjectSaver” (hence the name of the pattern). At the same time, it fits the requirements of the bridge pattern, since its respective definition and implementation reside on different class hierarchies. Isn’t this great? Of course it is!
After examining the definition for the previous bridge class, surely you’ll think that creating these kinds of structures with PHP 5 is actually a straightforward process, therefore let’s move on and learn together how to build the corresponding object saver classes that were defined before.
To see how these classes will be properly created, please click on the link below and keep reading.