コンポジションと注入
Coddyの「C開発者のためのPHP」コースのレッスン 37/48。
Cのコンポジションは値を埋め込むか、明示的な生存期間の所有権を持つコラボレーターを指すことができます。PHPオブジェクトは共有されたコラボレーターの識別子を保持します。コンストラクタ注入は選択を明示的にします。具体的な実装を密かに生成したり複製したりする代わりに、提供されたポリシーを呼び出します。
コンシューマーが必要とする契約の背後にコラボレーターを保持し、それを介して処理を委譲します。コンストラクタ注入は依存関係の選択を明示的にし、独立したテストダブルを可能にします。コンシューマーは具体的な実装を密かにインスタンス化したり、具体的なクラス名で分岐したりすべきではありません。それでは、提示されている差し替えポイントが無効になってしまいます。
C言語プログラム
#include <stdio.h>
struct Policy {
int factor;
int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
return self->policy->apply(self->policy, quantity);
}
int main(void)
{
struct Policy policy = {2, multiply};
struct Order order = {&policy};
printf("%d\n", order_total(&order, 3));
return 0;
}出力:
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 の実装に対応してください。
提供されているメインスクリプトは標準入力から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";
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ