Postanowiłem, że już pora, aby poznać wzorce projektowe. Poprosiłbym o sprawdzenie czy poprawnie zastosowałem wzorzec Metoda Fabrykująca. Jeżeli potrzeba dodatkowych informacji - pytajcie, bo na chwile obecną nic nie przychodzi mi do głowy

Interfejsy:
//FactoryAbstract.php abstract class FactoryAbstract { /** * @param $name * * @return object * @throws Exception */ public function createProduct( $name ) { include_once($this->getProductPath() . $name . ".php"); } else { throw new Exception("Plik '$name.php' nie istnieje."); } if ( class_exists( $name ) ) { return new $name(); } else { throw new Exception("Klasa '$name' nie istnieje."); } } /** * @return string */ protected abstract function getProductPath(); } //ProductAbstract.php abstract class ProductAbstract { protected $name; protected $price; /** * @return string */ public abstract function getName(); /** * @return string */ public abstract function getPrice(); }
Fabryki:
//FoodFactory.php include_once(ROOT . "FactoryAbstract.php"); class FoodFactory extends FactoryAbstract { /** * @return string */ protected function getProductPath() { return ROOT . 'food/'; } } //GlassFactory.php include_once(ROOT . "FactoryAbstract.php"); class GlassFactory extends FactoryAbstract { /** * @return string */ protected function getProductPath() { return ROOT . 'glass/'; } }
Produkty:
//glass/Kieliszek.php include_once(ROOT . "ProductAbstract.php"); class Kieliszek extends ProductAbstract { public function __construct() { $this->name = "Kieliszek gran party"; $this->price = 9.91; } public function getName() { return $this->name; } public function getPrice() { return $this->price; } } //food/Pierogi.php include_once(ROOT . "ProductAbstract.php"); class Pierogi extends ProductAbstract { public function __construct() { $this->name = "Pierogi ruskie delux, 10 sztuk."; $this->price = 12.99; } public function getName() { return $this->name; } public function getPrice() { return $this->price; } }
Kod wysyłający żądanie:
include_once(ROOT . "GlassFactory.php"); include_once(ROOT . "FoodFactory.php"); class Client { private $glassFactory; private $foodFactory; private $products; public function __construct() { //stawiamy fabryki - ich "produkty" posiadają wspólny interfejs (getName, getPrice) $this->glassFactory = new GlassFactory(); $this->foodFactory = new FoodFactory(); try { //tu dodać nowy produkt $this->glassFactory->createProduct( 'Kieliszek' ), $this->foodFactory->createProduct( 'Pierogi' ) ); } catch ( ErrorException $e ) { } } public function displayProducts() { foreach ( $this->products as $product ) { } } } $client = new Client(); $client->displayProducts();