组合与注入
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。支持任何 Fee 实现,而不仅限于 FlatFee。
提供的主脚本从标准输入读取一个 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 在线编译器