コンポジションとインジェクション
Coddyの「R開発者のためのPHP」コースのレッスン 37/48。
Rでは、ポリシー関数をリストに格納して処理を委譲でき、そのクロージャ環境に状態を保持できます。PHPでは、共有する協力オブジェクトの識別子を格納します。渡されたポリシーを尊重し、利用側の内部で隠れた代替オブジェクトを構築しないでください。
利用側が必要とする契約の背後に協力オブジェクトを格納し、それを通じて処理を委譲します。コンストラクターインジェクションを使うと、依存関係の選択が明示的になり、独立したテスト用代替オブジェクトを利用できます。利用側は、特定の実装をこっそりインスタンス化したり、具体的なクラス名に基づいて分岐したりすべきではありません。それでは、うたわれている置き換え可能な箇所の意味がなくなります。
Rプログラム
policy <- function(n) n*2; order <- list(policy=policy); total <- function(x) x$policy(3);cat(total(order),"\n",sep="")
ソースの出力:
6PHPプログラム
Clock.php
<?php
declare(strict_types=1);
interface Clock {public function hour():int;}
FixedClock.php
<?php
declare(strict_types=1);
require_once __DIR__."/Clock.php";class FixedClock implements Clock {public function hour():int{return 6;}}
Alarm.php
<?php
declare(strict_types=1);
require_once __DIR__."/Clock.php";class Alarm {public function __construct(private Clock $clock){}public function early():bool{return $this->clock->hour()<8;}}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/FixedClock.php";require_once __DIR__."/Alarm.php";echo (new Alarm(new FixedClock()))->early()?"early\n":"late\n";
PHPの出力:
earlyチャレンジ
簡単入力は[subtotal,fee]です。Feeはapply(int):intを定義します。FlatFeeはコンストラクターのamountを加算します。Checkout(Fee)のtotal(int):intは、注入されたFeeに処理を委譲します。FlatFeeだけでなく、あらゆるFeeの実装に対応してください。
用意されたmainスクリプトは標準入力から1つのJSON値を読み取り、指定された公開APIを確認して、結果を出力します。出力せずにモジュール宣言を実装してください。ランチャーを置き換えたり、モジュールから入力を読み取ったりしないでください。入力は指定された型と範囲を満たします。
Fee.php、FlatFee.php、Checkout.phpを編集してください。main.phpはロックされたエントリーファイルです。依存ファイルは相対ファイル名を指定したrequire_once __DIR__を使います。
自分で試してみよう
<?php
declare(strict_types=1);
require_once __DIR__."/Fee.php";
require_once __DIR__."/FlatFee.php";
require_once __DIR__."/Checkout.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$f=new class implements Fee {public function apply(int $cents):int{return $cents*2;}};ensure((new Checkout($f))->total(7)===14,"injected third party");
echo (string)(new Checkout(new FlatFee($input[1])))->total($input[0]),"\n";
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
R開発者のためのPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ