コンポジションとインジェクション
Coddyの「C++開発者向けPHP」コースのレッスン 37/48。
C++では、コラボレーターを値、参照、またはスマートポインターで注入できます。それぞれに異なるライフタイムと所有権のルールがあります。PHPでは、共有コラボレーターのオブジェクト識別子が保存されます。隠れた代替物を構築するのではなく、渡されたポリシーに従い、共有状態の変更を許可するかどうかを意図的に決めましょう。
コンシューマーが必要とする契約の背後にコラボレーターを保持し、それを通じて処理を委譲しましょう。コンストラクターインジェクションを使うと、依存関係の選択が明示され、独立したテスト用代替オブジェクトを使えるようになります。コンシューマーは、特定の実装を密かにインスタンス化したり、具体的なクラス名で分岐したりすべきではありません。そうすると、提示されている置き換え可能な箇所の意義が失われます。
C++プログラム
#include <iostream>
struct Policy {int factor;int apply(int n)const{return factor*n;}};
struct Service {const Policy& policy;int run(int n)const{return policy.apply(n);}};
int main() {
Policy p{2};Service s{p};std::cout<<s.run(3)<<"\n";
}
ソースの出力:
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 スクリプトは標準入力から 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";
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者向けPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ