PHP - Code Sample - Polymorphism Implementation - How to allow for expansion?

Posted by darga33 on Stack Overflow See other posts from Stack Overflow or by darga33
Published on 2012-10-16T04:59:31Z Indexed on 2012/10/16 5:00 UTC
Read the original article Hit count: 216

Filed under:
|
|

I've read numerous SO posts about Polymorphism, and also the other really good one at http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/ Good stuff!!!

I'm trying to figure out how a seasoned PHP developer that follows all the best practices would accomplish the following. Please be as specific and detailed as possible. I'm sure your answer is going to help a lot of people!!! :-)

While learning Polymorphism, I came across a little stumbling block. Inside of the PDFFormatter class, I had to use (instanceof) in order to figure out if some code should be included in the returned data. I am trying to be able to pass in two different kinds of profiles to the formatter. (needs to be able to handle multiple kinds of formatters but display the data specific to the Profile class that is being passed to it). It doesn't look bad now, but imagine 10 more kinds of Profiles!! How would you do this? The best answer would also include the changes you would make. Thanks sooooooo much in advance!!!!! Please PHP only! Thx!!!

File 1. FormatterInterface.php

interface FormatterInterface
{
    public function format(Profile $Profile);
}

File 2. PDFFormatter.php

class PDFFormatter implements FormatterInterface
{
    public function format(Profile $Profile)
    {
        $format = "PDF Format<br /><br />";
        $format .= "This is a profile formatted as a PDF.<br />";
        $format .= 'Name: ' . $Profile->name . '<br />';

        if ($Profile instanceof StudentProfile) {
            $format .= "Graduation Date: " . $Profile->graduationDate . "<br />";
        }

        $format .= "<br />End of PDF file";
        return $format;
    }
}

File 3. Profile.php

class Profile
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function format(FormatterInterface $Formatter)
    {
        return $Formatter->format($this);
    }
}

File 4. StudentProfile.php

class StudentProfile extends Profile
{
    public $graduationDate;

    public function __construct($name, $graduationDate)
    {
        $this->name = $name;
        $this->graduationDate = $graduationDate;
    }
}

File 5. index.php

//Assuming all files are included......

    $StudentProfile = new StudentProfile('Michael Conner', 55, 'Unknown, FL', 'Graduate', '1975', 'Business Management');

    $Profile = new Profile('Brandy Smith', 44, 'Houston, TX');

    $PDFFormatter = new PDFFormatter();
    echo '<hr />';
    echo $StudentProfile->format($PDFFormatter);
    echo '<hr />';
    echo $Profile->format($PDFFormatter);

© Stack Overflow or respective owner

Related posts about php

Related posts about php5