BuyController.class.php ※Facade適用前
<?php
class BuyController extends Controller
{
private $userId;
private $itemName;
private $itemPrice;
private $itemAmount;
private $money;
public function __construct($userId_, $itemName_, $itemPrice_, $itemAmount_, $money_)
{
$this->userId = $userId_;
$this->itemName = $itemName_;
$this->itemPrice = $itemPrice_;
$this->itemAmount = $itemAmount_;
$this->money = $money_;
}
public function Action_Buy()
{
try{
/**
* 商品の合計値段を計算します。
*/
$calcObj = new Calc($this->itemName, $this->itemAmount);
$payment = $calcObj->calcer();
/**
* 購入処理を行います。
*/
$resisterObj = new resister($payment, $this->money);
$resisterObj->resister();
/**
* クーポンの発行を行います。
*/
$coupon = new Coupon();
$coupon->publish($this->userId);
}catch(Exception $e){
$logger = new Logger();
$logger->write($e->getMessage());
throw new Exception( 'エラー発生:' .get_class($this) );
}
}
}
コントローラが肥大化する!
コントローラにModel部分の処理が入ってきている…。
Facadeパターンを適用する
Controllerで行っていたModelの処理を、Facadeクラスを作成してそちらに一元の窓口にする。Controllerがすっきりする。
Buyfacade.class.php
<?php
class BuyFacade
{
public function execute($userId, $itemName, $itemPrice, $itemAmount, $money)
{
try{
/**
* 商品の合計値段を計算します。
*/
$calcObj = new Calc($this->itemName, $itemAmount);
$payment = $calcObj->calcer();
/**
* 購入処理を行います。
*/
$resisterObj = new resister($payment, $money);
$resisterObj->resister();
/**
* クーポンの発行を行います。
*/
$coupon = new Coupon();
$coupon->publish($userId);
}catch(Exception $e){
$logger = new Logger();
$logger->write($e->getMessage());
throw new Exception( 'エラー発生:' .get_class($this) );
}
}
}
BuyController.class.php ※Facade適用後
<?php
class BuyController extends Controller
{
private $userId;
private $itemName;
private $itemPrice;
private $itemAmount;
private $money;
public function __construct($userId_, $itemName_, $itemPrice_, $itemAmount_, $money_)
{
$this->userId = $userId_;
$this->itemName = $itemName_;
$this->itemPrice = $itemPrice_;
$this->itemAmount = $itemAmount_;
$this->money = $money_;
}
public function Action_Buy()
{
try{
$buyFacadeObj = new BuyFacade();
$buyFacadeObj->execute($this->userId, $this->itemName, $this->itemPrice, $this->itemAmount, $this->money);
}catch(Exception $e){
$logger = new Logger();
$logger->write($e->getMessage());
throw new Exception( 'エラー発生:' .get_class($this) );
}
}
}
@see http://hamuhamu.hatenablog.jp/entry/2015/08/16/222835
![PHP Template Methodパターン [PHPによるデザインパターン入門]](https://www.yuulinux.tokyo/contents/wp-content/uploads/2017/09/phpDP_20190407_1-150x150.jpg)
