示例#1
0
文件: index.php 项目: Overfinch/oop
}
class ProductFactory
{
    // сама фабрика
    private $_types = [];
    public function __construct()
    {
        // массив из разрешенных типов
        $this->_types = ['keyboard' => 'keyboard', 'mouse' => 'mouse'];
    }
    public function make($product)
    {
        if (!array_key_exists($product['type'], $this->_types)) {
            // проверяем разрешен ли такой тип
            throw new InvalidArgumentException("Тип " . $product['type'] . " не найден!");
        }
        $class_name = $this->_types[$product['type']];
        // имя класса называется именем переданного типа
        return new $class_name($product);
        // создаётся объект нужного класса
    }
}
$products = [['id' => 1, 'model' => 'LOGITECH K810', 'price' => 150, 'type' => 'keyboard'], ['id' => 2, 'model' => 'LOGITECH WIRELES MOUSE G700', 'price' => 140, 'type' => 'mouse']];
$productsFactory = new ProductFactory();
$cart = [];
foreach ($products as $product) {
    $cart[] = $productsFactory->make($product);
}
var_dump($cart);
echo $cart[1]->getPrice();
// например достаём цену
 /**
  * @throws \Exception
  */
 public function makeObj()
 {
     ProductFactory::build('UserGeneratorFactory');
 }
 private function get_data($data)
 {
     // get id
     $this->receipt_id = $data['receipt_id'];
     //get the time of receipt
     $this->time = $data['time'];
     // get clients data
     if (is_null($data['clients'])) {
         $this->clients = null;
     } else {
         $this->clients = new Customer();
         $this->clients->get_data_from_array($data['clients']);
     }
     //get receiver data
     if (is_null($data['receiver'])) {
         $this->receiver = null;
     } else {
         $this->receiver = new Employee();
         $this->receiver->get_data_from_array($data['receiver']);
     }
     //get list of product
     $list_data_product = $data['list_product'];
     // for each value in data list product, push into the list product
     foreach ($list_data_product as $value) {
         //get the product factory to get the right product object type
         $product = ProductFactory::create_product($value);
         //add product to list_product
         $this->add($product);
     }
 }
    public function isAvailable() : bool;
    public function warehouses() : array;
}
class Foo implements Product
{
    public function name() : string
    {
        return 'FooProduct';
    }
    public function ammount() : int
    {
        return 15;
    }
    public function isAvailable() : bool
    {
        return $this->ammount > 0;
    }
    public function warehouses() : array
    {
        return ['PL', 'DE', 'CZ'];
    }
}
class ProductFactory
{
    public static function fromName($name) : Product
    {
        return new $name();
    }
}
$fooProduct = ProductFactory::fromName('Foo');
echo $fooProduct->name() . ', ammount = ' . $fooProduct->ammount();