CKTIS / PHP
Programma-architectuur
Scheid prijsberekening en gegevensbron door een interface in de dienst te injecteren.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(private PriceSource $source) {}Scheid prijsberekening en gegevensbron door een interface in de dienst te injecteren. De aanroeper koppelt adapter en dienst. Gebruik null voor een ontbrekende prijs zodat nul een geldige prijs blijft. Een testadapter controleert de berekening zonder 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]
Voorbeelden
<?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)]);
Resultaat
[0,12]