합성과 주입
Coddy의 Go 개발자를 위한 PHP 코스 레슨. 48개 중 37번째.
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는 생성자 amount를 더합니다. Checkout(Fee)의 total(int):int는 주입된 Fee에 처리를 위임합니다. FlatFee뿐 아니라 모든 Fee 구현을 지원하세요.
제공된 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 컴파일러