组合与注入
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())
}
源程序输出:
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 会将构造函数中的金额加上去。Checkout(Fee) 的 total(int):int 会委托给注入的 Fee。支持任何 Fee 实现,而不只是 FlatFee。
提供的 main 脚本会从标准输入读取一个 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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 PHP中的所有课
自己练习: PHP 在线编译器