コンポジションと注入
Coddyの「Swift開発者のためのPHP」コースのレッスン 37/48。
Swiftのインジェクションでは、値の協力オブジェクトまたは参照を格納でき、プロトコルによって動作を差し替えられます。PHPのプロパティは、共有される協力オブジェクトのオブジェクト識別子を保持します。渡されたポリシーに従い、隠れた具体的な代替実装を構築するのではなく、変更に関する期待を定義しましょう。
利用側が必要とする契約の背後に協力オブジェクトを格納し、そのオブジェクトを通じて処理を委譲します。コンストラクターインジェクションにより、依存関係の選択が明示され、独立したテスト用代替オブジェクトを使用できます。利用側は特定の実装をひそかにインスタンス化したり、具体的なクラス名に基づいて分岐したりすべきではありません。それでは、うたわれている差し替えポイントが機能しなくなります。
Swiftプログラム
struct Policy { let factor: Int; func apply(_ n: Int) -> Int { n * factor } }
struct Order { let policy: Policy; func total(_ n: Int) -> Int { policy.apply(n) } }
print(Order(policy: Policy(factor: 2)).total(3))
ソースの出力:
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チャレンジ
簡単入力は[小計,手数料]です。Feeはapply(int):intを定義し、FlatFeeはコンストラクターで受け取った金額を加算します。Checkout(Fee)のtotal(int):intは、注入されたFeeに処理を委譲します。FlatFeeだけでなく、あらゆるFeeの実装に対応してください。
用意されたmainスクリプトは、標準入力からJSON値を1つ読み取り、指定された公開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";
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Swift開発者のためのPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ