Composition and Delegation
Lesson 38 of 48 in Coddy's Lua for PHP Developers course.
PHP objects can hold other objects as collaborators, and assigning an object handle does not clone it. Lua tables can hold collaborator tables with the same sharing behavior. A pricing model stores a policy and delegates calculation to its apply method. This keeps state ownership separate from the pricing rule. Calls with a colon supply the policy as receiver. A different collaborator implementing the same method can be passed without changing the model's calculation code.
PHP
<?php
class Policy {
public function apply(int $n): int { return $n * 2; }
}
class Order {
private Policy $policy;
public function __construct(Policy $policy) { $this->policy = $policy; }
public function total(): int { return $this->policy->apply(3); }
}
echo (new Order(new Policy()))->total(), "\n";Lua
local policy={}
function policy:apply(n) return n*2 end
local order={policy=policy}
function order:total() return self.policy:apply(3) end
print(order:total())Porting trap
Do not reconstruct a policy from a known factor inside the model: that defeats delegation and fails when a custom collaborator computes differently. Store and invoke the object supplied by the caller. Share mutable collaborators only when that shared state is intentional.
Challenge
EasyImplement a pricing policy in policy.lua with apply(n) multiplying n by a stored factor. Model stores the policy and exposes total(n). Input is factor and quantity. Return the delegated total.
Edit app.lua, model.lua, policy.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Public API checks: Policy.new(factor) provides apply(n). Model.new(policy) must delegate total(n) to the supplied policy, including a custom object implementing apply, and retain that collaborator independently. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
Try it yourself
-- Public API checks
do
local Model=require("model")
local Policy=require("policy")
local p=Policy.new(3)
assert(p:apply(4)==12 and p:apply(0)==0,"policy multiplies by its factor")
local a=Model.new(p)
assert(a:total(2)==6,"model must use its pricing policy")
local calls=0
local custom={apply=function(self,n) calls=calls+1;return n+7 end}
local b=Model.new(custom)
assert(b:total(5)==12 and calls==1,"model must delegate to the supplied collaborator")
assert(a:total(1)==3,"models retain their own policy")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for PHP Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
PHP Lists to Dense TablesAssociative Arrays and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Readable ObjectsComposition and DelegationPrototype Lookup ChainsPolymorphism by ProtocolValue Equality MetamethodsRecap: Dispatch ReportsPractice on your own: Online Lua compiler