Верная ли такая реализация?

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
rootMan
Сообщения: 3
Зарегистрирован: 2020.07.15, 23:16

Верная ли такая реализация?

Сообщение rootMan »

Код: Выделить всё

    public function actionUpdate($id)
    {
        $product = $this->findModel($id);
        
        if (!$updateProduct = Yii::createObject(ProductUpdate::class, [$product, Yii::$app->request->post()])->execute()) {
            return $this->redirect(['/product/view', 'id' => $product->getId()]);
        }
        return $this->render('update', [
            'product' => $product,
            'model' => $updateProduct,
        ]);
    }
//

Код: Выделить всё

class ProductUpdate
{
    protected $product;
    protected $post;
    
    
    public function __construct(\app\models\Product $product, array $post)
    {
        $this->product = $product;
        $this->post = $post;
    }
    
    protected function createUpdateForm()
    {
        $productForm = new ProductForm($this->product);
        $productForm->attributes = $this->product->attributes;
        
        if (empty($this->post)) {
            return $productForm;
        }
        $productForm->load($this->post);
        Yii::$app->session->setFlash('success', 'Вы успешно изменили товар!');
        $productForm->save();
        return $productForm;
    }
    
    protected function checkStatus()
    {
        if ($this->product->status == $this->product::STATUS_SOLD_OUT || $this->product->status == $this->product::STATUS_PARTIAL_SALE) {
            Yii::$app->session->setFlash('error', 'Вы не можете изменить этот товар, т.к. он уже продан, либо частично продан!');
            return false;
        }
        return true;
    }
    
    public function execute()
    {
        if ($this->checkStatus()) {
            return $this->createUpdateForm ();
        }
        return false;
    }
    
}
Ответить