@blog.justoneplanet.info

日々勉強

PHPでデザインパターン:Builder(ビルダー)

Item.class.php

<?php
class Item
{
    private $_title;
    private $_url;
    private $_date;
    public function __construct($title, $url, $date)
    {
        $this->_title = $title;
        $this->_url  = $url;
        $this->_date = $date;
    }
    public function getTitle()
    {
        return $this->_title;
    }
    public function getUrl()
    {
        return $this->_url;
    }
    public function getDate()
    {
        return $this->_date;
    }
}

NewsDirector.class.php

<?php
require_once 'class/NewsDirector.class.php';

class NewsDirector
{
    private $_builder;
    private $_url;
    public function __construct(NewsBuilder $builder, $url)
    {
        $this->_builder = $builder;
        $this->_url     = $url;
    }
    public function getNews()
    {
        $list = $this->_builder->parse($this->_url)
        return $list
    }
}

NewsBuilder.class.php

<?php
interface NewsBuilder
{
    public function parse($data);
}

FeedNewsBuilder.class.php

<?php
require_once 'Item.class.php';
require_once 'NewsBuilder.class.php';

class FeedNewsBuilder implements NewsBuilder
{
    public function parse($url)
    {
        $data = new SimpleXmlElement($url, null, true);
        if($data){
            foreach($data->item as $item){
                $dc = $item->children('http://purl.org/dc/elements/1.1/');
                $list[] = new News($item->title, $item->link, $dc->date);
            }
            return $list;
        }
    }
}

index.php

クライアントとやり取りするフロント部分だ。

<?php
require_once 'class/NewsDirector.class';
require_once 'class/FeedNewsBuilder.class.php';

$builder = new FeedNewsBuilder();
$url = 'http://blog.justoneplanet.info/feed/';
$director = new NewsDirector($builder, $url);
foreach($director->getNews() as $article){
    $data = array(
        'date'  => $article->getDate(),
        'url'   => $article->getUrl(),
        'title' => $article->getTitle()
    );
}

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment