A
A
Anton R.2019-11-16 23:49:10
OOP
Anton R., 2019-11-16 23:49:10

OOP exercise (objective analysis) on the free topic "Cooking borscht", what do you say?

Like most OOP learners, I have difficulties when I need to apply all the theory that I draw from books and the Internet, in theory everything is quite simple, but when it comes to practical application on live projects, there is some kind of incomprehensible stupor. In order to gradually eliminate this stupor, I decided to practice precisely in "objective analysis" using the example of the process of preparing borscht, and this is what happened to me.
I presented the cooking process from several steps: buying products, preparing products, cooking borscht in a saucepan, created classes, methods.
Well, the actual code itself (it’s scary in places, I know, but who started right away perfectly?):

<?php

// ---------------- Класс Повар: покупает продукты, нарезает продукты, собирает ингредиенты ------

class Cook {

    public $money = 100;
    public $rawFood;
    public $ingredients = array();

    public function buyFood(Shop $shop) // Покупка продуктов.
    {
        $rawFood = $shop->sellFood($this->money);
        if($rawFood){
            $this->rawFood = $rawFood;
            return $this;
        }
        return $this;
    }

    public function prepareFood() // Подготовка продуктов.
    {
        foreach($this->rawFood->stock as $food)
        {
            $ingredient = $this->cut($food);
            $this->ingredients[] = $ingredient;
        }
        return $this;
    }

    public function cut($food) // Нарезка продуктов.
    {
       $cutted = $food; // Здесь некий процесс "нарезки", не придумал как отобразить.
    return $cutted;
    }

    public function combineFood(Pot $pot) // Складываем нарезанное в кастрюлю.
    {
        $pot->containingIngredients($this->ingredients);
        return $this;
    }


}

// ---------------- Класс Магазин: содержит продукты, продает продукты --------------------------

class Shop {

    public $foodStorage;
    public $productsTotalPrice = null;

    public function __construct(){
        $this->foodStorage = new FoodStock(); // Заполняем магазинные полки продуктами.
    }

    public function sellFood($money) // Продажа продуктов
    {
        $totalPrice = null;
        for($i = 0; $i < count($this->foodStorage->stock); $i++) {
            $totalPrice += $this->foodStorage->stock[$i]->price;
        }
        $this->productsTotalPrice = $totalPrice;

        if($this->productsTotalPrice < $money){ // Проверка хватит ли денег на всё.
            return $this->foodStorage;
        }
        else {
            return false;
        }
    }
}

// ---------------- Класс Плита: нагревает кастрюлю ---------------------------------------------

class Stove {

    public $temperature;

    public function turnOn() // Включаем плиту.
    {
        $this->temperature = 100;
        return $this->temperature;
    }
}

// ---------------- Класс Кастрюля: содержит воду и ингредиенты, варит борщ ---------------------

class Pot {

    public $water = null;
    public $containedIngredients = null;
    public $temperature = null;
    public $timer = null;

    public function addWater() // Добавляем воду.
    {
        $this->water = '2000 ml';
        return $this;
    }

    public function boil(Stove $stove) // Варка.
    {
        $temperature = $stove->turnOn();
        $this->temperature = $temperature;
        $this->timer = 60;
        if($temperature = 100 && $this->timer >= 60)
        {
            echo "Приготовлено!";
        }
    }

    public function containingIngredients($ingredients) // Заполнение кастрюли ингредиентами.
    {
        $this->containedIngredients = $ingredients;
        return;
    }
}

// ---------------- Класс Склад: содержит разные продукты --------------------------------

class FoodStock {
    public $stock = [];

    public function __construct(){
        $potato = new RawFood('25', 'potato');
        $carrot = new RawFood('15', 'carrot');
        $onion = new RawFood('20', 'onion');
        $meat = new RawFood('35', 'meat');

        // Вот тут хрень конечно но что-то не додумался как заполнить массив  циклом.
        $this->stock[] = $potato;
        $this->stock[] = $carrot;
        $this->stock[] = $onion;
        $this->stock[] = $meat;
    }
}

// ---------------- Класс Продукт: содержит цену и имя продукта ---------------------------

class RawFood {
    public $price;
    public $name;

    public function __construct($price, $name){
        $this->price = $price;
        $this->name = $name;
    }
}

// ---------------- ПРОЦЕСС ПРИГОТОВЛЕНИЯ ------------------------------------------------

$cook = new Cook();
$shop = new Shop(); // Заполняется автоматически.
$pot = new Pot();
$stove = new Stove();

$cook
    ->buyFood($shop)
    ->prepareFood()
    ->combineFood($pot);

$pot
    ->addWater()
    ->boil($stove);

And it even seems to work (at least it doesn't throw Notice, Warning and FatalError):
5dd062cc63480278751989.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kova1ev, 2019-11-17
@kova1ev

I didn’t really look at the code, sorry, I was guided by the comments in the code.
The main thing, IMHO, in OOP is the combination of some data and methods that change this data into a single logical entity called a "class". You somehow have too many classes, and somehow it is not clear they are collected in logical entities. For example, the class "Cook" - there from the data I see the amount of money and an array with products. It doesn't really fit with the "Cook" entity. Or the class "Shop" - in the task of cooking borscht, what for to produce such entities as a warehouse of a store, for example, or the total cost of products available in the store. I understand that the task far-fetched, but still.
All of the above is purely IMHO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question