Menu
CoddyTech

コンポジションとインジェクション

Coddyの「Go開発者のためのPHP」コースのレッスン 37/48。

Goでは、動的な実装がポリシーを提供するインターフェース値を注入できます。ポインターと値のどちらを選ぶかによって、共有状態に影響します。PHPのオブジェクトプロパティは、協力オブジェクトへの共有識別子を保持します。注入された振る舞いを尊重し、利用側の内部で隠れた代替オブジェクトを構築しないでください。

利用側が必要とする契約を通じて協力オブジェクトを保持し、そのオブジェクトに処理を委譲します。コンストラクターインジェクションによって依存関係の選択が明示され、独立したテスト用ダブルを使えるようになります。利用側は、特定の実装をひそかにインスタンス化したり、具象クラス名を条件分岐に使ったりするべきではありません。それでは、置き換え可能だと謳っている箇所の意味がなくなります。

Goプログラム

package main
import ("fmt")
type Policy interface {Apply(int)int}
type DoublePolicy struct{}
func(DoublePolicy) Apply(n int)int{return n*2}
type Order struct{Policy Policy}
func(o Order) Total()int{return o.Policy.Apply(3)}
func main(){
order:=Order{Policy:DoublePolicy{}}; fmt.Println(order.Total())
}

実行結果:

6

PHPプログラム

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
challenge icon

チャレンジ

簡単

入力は[小計,手数料]です。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";
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Go開発者のためのPHPのすべてのレッスン

自分で練習してみよう: PHPオンラインコンパイラ