컴포지션과 주입
Coddy의 Rust 개발자를 위한 PHP 코스 레슨. 48개 중 37번째.
Rust 인젝션은 협력 객체를 소유하거나, 빌리거나, 명시적인 스마트 포인터를 통해 공유할 수 있습니다. PHP 객체 속성은 빌림 검사를 하지 않고 공유 식별자를 유지합니다. 제공된 정책을 따르고, 대체 객체를 조용히 구성하는 대신 변경 및 수명에 대한 기대치를 신중하게 정하세요.
소비자가 필요로 하는 계약 뒤에 협력 객체를 저장하고, 이를 통해 작업을 위임하세요. 생성자 인젝션은 의존성 선택을 명시적으로 만들고 독립적인 테스트 대역을 사용할 수 있게 해 줍니다. 소비자가 특정 구현을 몰래 인스턴스화하거나 구체적인 클래스 이름에 따라 분기해서는 안 됩니다. 그러면 공개된 대체 지점의 목적이 무산됩니다.
Rust 프로그램
struct Policy{factor:i32}
impl Policy{fn apply(&self,n:i32)->i32{n*self.factor}}
struct Order{policy:Policy}
impl Order{fn total(&self,n:i32)->i32{self.policy.apply(n)}}
fn main() {
let order=Order{policy:Policy{factor:2}}; println!("{}",order.total(3));
}
소스 출력:
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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Rust 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러