HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Is this a qualified OOP script in PHP?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisscriptqualifiedphpoop

Problem

class Youtube
{
    private $url = null;
    private $id;

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

    protected function parseUrl($url)
    {

        if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
            $this->id = $match[1];
        }
        else
        {
            throw new exception('Cannot find an ID!');
        }

    }

    public function getVideo($width='560', $height='315')
    {
        $video = id" frameborder="0" allowfullscreen>
EOF;

        return $video;
    }

}

$sistar = new Youtube('http://www.youtube.com/watch?v=JtVhwsACgTw');
print $sistar->getVideo();

$twoneone = new Youtube('http://www.youtube.com/watch?v=LUrUPzLm5SI');
print $twoneone->getVideo();


This is my first object-oriented script in PHP (I hope it's not too bad in general). I know I should do more validation and commenting within the code. Do you have any suggestions for improving the quality of the code?

Solution

Pinoniq has the right idea, which can be taken a bit further:

VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://youtube.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();


Here, the VideoFactory can parse a URL. The createVideo method would return a subclass of Video, which is a YouTubeVideo. However, the implementation need not be dependent on YouTube. This allows you to also write:

VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://vimeo.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();


You'll note that the only item that changed is the URL, but both video formats can be embedded.

Code Snippets

VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://youtube.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();
VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://vimeo.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();

Context

StackExchange Code Review Q#30297, answer score: 3

Revisions (0)

No revisions yet.