CKTIS / PHP
Program architecture
Place the pricing rule behind a service and inject an interface for the changing data source.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(private PriceSource $source) {}Place the pricing rule behind a service and inject an interface for the changing data source. The caller composes the concrete adapter with the service. A missing quote is represented by null, so a valid zero price survives. A test adapter exercises the rule without connecting to a database.
interface PriceSource{function quote(string $id):?int;}class PriceList implements PriceSource{function __construct(private array $prices){} function quote(string $id):?int{return $this->prices[$id]??null;}}
class Checkout{function __construct(private PriceSource $source){}function total(string $id,int $n):int{return ($this->source->quote($id)??throw new DomainException())*$n;}}
$c=new Checkout(new PriceList(["free"=>0,"ink"=>4]));echo json_encode([$c->total("free",3),$c->total("ink",3)]);
[0,12]
Examples
<?php
interface PriceSource{function quote(string $id):?int;}class PriceList implements PriceSource{function __construct(private array $prices){} function quote(string $id):?int{return $this->prices[$id]??null;}}
class Checkout{function __construct(private PriceSource $source){}function total(string $id,int $n):int{return ($this->source->quote($id)??throw new DomainException())*$n;}}
$c=new Checkout(new PriceList(["free"=>0,"ink"=>4]));echo json_encode([$c->total("free",3),$c->total("ink",3)]);
Result
[0,12]