CKTIS / PHP
Architecture du programme
Séparez le calcul du prix de sa source en injectant une interface dans le service.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
public function __construct(private PriceSource $source) {}Séparez le calcul du prix de sa source en injectant une interface dans le service. L’appelant assemble l’adaptateur et le service. Marquez un prix absent par null pour garder le prix zéro valide. Un adaptateur de test vérifie le calcul sans base de données.
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]
Exemples
<?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)]);
Résultat
[0,12]