Factoring Content Boxes with the Factory Pattern in PHP 5 - Building different types of content boxes
(Page 3 of 4 )
As I stated in the section that you just read, to complete the schema dictated by the factory pattern, it's necessary to define some additional classes. These classes will display the complete set of content boxes that you learned previously.
Here are the corresponding signatures for these new classes. Take a look at them, please:
// define abstract 'ContentBox' class
abstract class ContentBox{
private $title;
private $content;
abstract public function __construct($title,$content);
abstract public function display();
}
// define concrete 'GreyContentBox' class
class GreyContentBox extends ContentBox{
public function __construct($title,$content){
if(!$title){
throw new Exception('A title for the content box must be
provided.');
}
if(!$content){
throw new Exception('The content for the box must be
provided.');
}
$this->title=$title;
$this->content=$content;
}
public function display(){
return '<div class="greybox"><h2>'.$this-
>title.'</h2><p>'.$this->content.'</p></div>';
}
}
// define concrete 'BlueContentBox' class
class BlueContentBox extends ContentBox{
public function __construct($title,$content){
if(!$title){
throw new Exception('A title for the content box must be
provided.');
}
if(!$content){
throw new Exception('The content for the box must be
provided.');
}
$this->title=$title;
$this->content=$content;
}
public function display(){
return '<div class="bluebox"><h2>'.$this-
>title.'</h2><p>'.$this->content.'</p></div>';
}
}
// define concrete 'YellowContentBox' class
class YellowContentBox extends ContentBox{
public function __construct($title,$content){
if(!$title){
throw new Exception('A title for the content box must be
provided.');
}
if(!$content){
throw new Exception('The content for the box must be
provided.');
}
$this->title=$title;
$this->content=$content;
}
public function display(){
return '<div class="yellowbox"><h2>'.$this-
>title.'</h2><p>'.$this->content.'</p></div>';
}
}
As you can see, the three concrete classes shown above present the same "display()" method, which comes in useful for displaying a concrete type of content box. In addition, the classes' constructor accepts some simple input parameters, like the title and contents that will be housed by the box in question. Quite simple, right?
All right, I believe that at this point I provided you with all the PHP classes required to dynamically display a bunch of content boxes on any web page. Since I know you may want to see how all these components can be linked with each other, in the section to come I'm going to develop an example which hopefully will show you the functionality of the factory pattern in a real world situation.
To learn more about how this practical example will be developed, click on the link below and read the next few lines.
Next: Displaying web page content boxes via the factory pattern >>
More PHP Articles
More By Alejandro Gervasio