HomePHP Page 5 - Introducing Bridge Classes with PHP 5
Seeing the bridge pattern in action - 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.
Logically, the best way to understand how the bridge pattern works rests on setting up an example where all the classes that were created previously are used together in the same script. In accordance with this, below I coded a few simple snippets which show how the bridge class saves a target object first to an array, then a text file, and finally a cookie. Thus, take a look at the list of try-catch blocks shown below:
try{
// instantiate 'Message' object
$msg=new Message('This a test string that will be saved later
on');
// instantiate 'BridgeObjectSaver' object, and indicate that
target object will be saved to array
$bObjSaver=new BridgeObjectSaver($msg,'array');
// save target object to array
$bObjSaver->save();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
try{
// instantiate 'Message' object
$msg=new Message('This a test string that will be saved later
on');
// instantiate 'BridgeObjectSaver' object, and indicate
that target object will be saved to file
$bObjSaver=new
BridgeObjectSaver($msg,'file');
//
save target object to text file
$bObjSaver->save();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
try{
// instantiate 'Message' object
$msg=new Message('This a test string that will be saved later
on');
// instantiate 'BridgeObjectSaver' object, and indicate that
target object will be saved to a cookie
$bObjSaver=new BridgeObjectSaver($msg,'cookie');
// save target object to a cookie
$bObjSaver->save();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
As you’ll realize, the above examples demonstrate a clear implementation of the bridge pattern with PHP 5. Of course, if you’re interested in learning more on this pattern, feel free to modify the original source code that I showed here, and experiment with developing more complex examples.
Conclusion
In this first part of the series, I introduced the core concepts of the bridge design pattern in PHP 5. As you hopefully learned, this pattern allows you to separate a given class from its corresponding implementation, without using abstract classes.
In the next part, I’m going to show you how to apply this pattern to create different data validation classes. The experience is really promising, therefore you don’t have any excuses to miss it!