Menu
CoddyTech

합성과 주입

Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 37번째.

C 컴포지션은 값을 내장하거나 명시적인 수명 소유권을 지닌 협력자를 가리킬 수 있습니다. PHP 객체는 공유 협력자에 대한 식별자를 가집니다. 생성자 주입은 이 선택을 명시적으로 만듭니다. 구체적인 구현을 은밀하게 생성하거나 복제하는 대신 제공된 정책(policy)을 호출하세요.

소비자가 필요로 하는 계약 뒤에 협력자를 저장하고 이를 통해 작업을 위임하세요. 생성자 주입은 의존성 선택을 명시적으로 만들고 독립적인 테스트 더블을 가능하게 합니다. 소비자가 은밀하게 특정 구현을 인스턴스화하거나 구체적인 클래스 이름에 따라 분기해서는 안 됩니다. 이는 제공하려는 교체 지점의 목적을 저해합니다.

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;
}

소스 출력:

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

챌린지

쉬움

입력은 [subtotal,fee]입니다. Fee는 apply(int):int를 정의하며, FlatFee는 생성자의 amount를 더합니다. Checkout(Fee)의 total(int):int는 주입된 Fee에 위임합니다. FlatFee뿐만 아니라 모든 Fee 구현을 지원해야 합니다.

제공된 메인 스크립트는 표준 입력에서 하나의 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";
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 PHP의 모든 레슨

직접 연습해 보세요: 온라인 PHP 컴파일러