Adapter Sample Code

Read this article about design patterns: ADAPTER -- also called WRAPPER --
implemented in PHP 5

229__adaptersample.gif
Figure 1. Class diagram of the adapter pattern

The adapter pattern -- also called wrapper

Date:
5 Dec 2008

The Adapter pattern lets you use an original exisiting class to meet your new class needs.
When you need to use a class or an interface that is different from your actual new class, and you cannont change the original exisiting class, this pattern will let you turn your actual class into the original existing class without changing it by using an adapter that will wrap your new object. (See figure 1)

So, we have:
  1. An original existing class and we cannot change its source code
  2. An adapter class that will extend from the original class
  3. Your new class to be adapted

Sample code:

/**
 * AdapterPatternSample - class.Address.php
 *
 * Adapter pattern sample, this is the original class
 * and we cannot change its source code
 *
 * 05 Dec 2008
 * @author freedelta http://freedelta.free.fr
 */

class Address    
{  
    private $type = null;   
    private $description = null;

    // Setters and getters block
    public function setType($type)
    {
        $this->type=$type;
    }
   
    public function getType()
    {        
        return $this->type;
    }
   
    public function setDescription($description)
    {
        $this->description=$description;     }
    public function getDescription()
    {
        return $this->description;
    }
} /* end of class Address */


/**
 * AdapterPatternSample - class.EmailAdapter.php
 *
 * This is the adapter class that will wrap  * our Email object
 *
 * 05 Dec 2008
 * @author freedelta http://freedelta.free.fr
 */

class EmailAdapter extends Address {   
    /**
     * The object to be wrapped (adaptee) is passed here
     */
    public function __construct(Email $email)     {
        // Inherited methods from parent class Address
        $this->setType("email");
        $this->setDescription($email->getEmailAddress()); // Passing the Email object here
    }

} /* end of class EmailAdapter */


/**
 * AdapterPatternSample - class.Email.php
 *
 * This is the new class that is going to be wrapped or adapted
 * to use the methods of the parent class Address
 *
 * 05 Dec 2008
 * @author freedelta http://freedelta.free.fr
 */

class Email
{
   
    private $emailAddress = null;
    public function setEmailAddress($address)     {
        $this->emailAddress=$address;
    }
    public function getEmailAddress()     {        
        return $this->emailAddress;
    }

} /* end of class Email */

// -- SAMPLE USE
print str_repeat("-",80)." ";

$email=new Email();
$email->setEmailAddress("user@adaptersample.com");

$address=new EmailAdapter($email);

print $address->getType()." ";
print $address->getDescription();