Composition and injection
Lesson 37 of 48 in Coddy's PHP for GDScript Developers course.
GDScript composition stores a collaborator and delegates operations to it, as the policy object here demonstrates. PHP object properties likewise retain shared identifiers. Honor the injected collaborator and decide whether its state may mutate instead of quietly replacing it.
Store a collaborator behind the contract the consumer needs and delegate work through it. Constructor injection makes dependency selection explicit and allows independent test doubles. The consumer should not instantiate a specific implementation secretly or branch on concrete class names. That would defeat the advertised replacement point.
GDScript program
extends SceneTree
class Policy:
var factor
func _init(value):
factor = value
func apply(n):
return n * factor
class Model:
var policy
func _init(chosen_policy):
policy = chosen_policy
func total(n):
return policy.apply(n)
func _init():
var model = Model.new(Policy.new(4))
print(model.total(3))
quit()Source output:
12PHP program
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 output:
earlyChallenge
EasyInput is [subtotal,fee]. Fee defines apply(int):int; FlatFee adds its constructor amount. Checkout(Fee) total(int):int delegates to its injected Fee. Support any Fee implementation, not only FlatFee.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Fee.php, FlatFee.php, Checkout.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?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";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for GDScript Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents7Object contracts
Visibility and invariantsStatic methods and factoriesInheritance and overridingInterfaces are nominalComposition and injectionRecap: selectable policy2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler