LoginSignup
5
5

More than 5 years have passed since last update.

PHPで使うGoFパターン ひとり Advent Calendar - ビルダー

Last updated at Posted at 2012-07-26

ビルダーってなに?

要するにインスタンスを生成するための手順を隠蔽するパターンのひとつですね。
ビルダーそのものの抽象度が高いところに面白さがあります。

ビルダーの構造

  • ディクレター - ビルダーを使う機能を持つ
  • ビルダー - インスタンスを生成して目的に応じたプロパティを設定する機能を持つ
  • 生成物 - 生成されるもの

ディレクター, ビルダーインターフェース, ビルディングまで

<?php

/* Builder */
interface IDataStoreBuilder {
  public function setDriver ();
  public function getResult ();
}

/* Direcotr */
class DataStoreDirector {
  private $_Builder = null;
  public function __construct ( $builder ) {
    if ( !( $builder instanceof IDataStoreBuilder ) ) 
      throw new Exception ( 
        'ビルダーじゃなきゃ嫌だもん' 
      );
    $this->_Builder = $builder;
  }

  public function build () {
    $this->_Builder->setDriver ();
    return $this->_Builder->getReslt();
  }
}

/* Building */
class DataStore {
  private $_Driver = null;

  public function __construct () {
  }

  public function setDriver ( $driver ) {
    $this->_Driver = $driver;
  }

  public function addRow ( $row ) {
    $this->_Driver->addRow ( $row );
  }

  public function deleteRow ( $row_num ) {
    $this->_Driver->deleteRow ( $row_num );
  }

  public function updateRow ( $row_num, $row ) {
    $this->_Driver->updateRow ( $row_num, $row );
  }

  public function find ( $filter ) {
    $this->_Driver->find ( $filter );
  }
}

実ビルダー

<?php

/* builders */
class FileStoreBuilder implements IDataStoreBuilder {
  private $_DataStore = null;
  public function __construct () {
    $this->_DataStore = new DataStore ();
  }

  public function setDriver () {
    $this->_DataStore->setDriver ( new FileDriver ( '/path/to/store' ) );  
  }
  public function getResult () {
    return $this->_DataStore;
  }
}

class DBStoreBuilder implements IDataStoreBuilder {
  private $_DataStore = null;
  public function __construct () {
    $this->_DataStore = new DataStore ();
  }

  public function setDriver () {
    $this->_DataStore->setDriver ( new DBDriver ( new DBConnection ( 
      'mysql://user:pass@server/db' 
    )));  
  }

  public function getResult () {
    return $this->_DataStore;
  }
}

// DBとかFileとかの実クラスは省略 m(_ _)m

コンローラ (クラスじゃないけど)

$fd = new DataStoreDirector ( new FileStoreBuilder() );
$dd = new DataStoreDirector ( new DBStoreBuilder() );

$file = $fd->build();
$db   = $dd->build();
5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5