O
O
Orbb2018-05-05 19:10:35
Yii
Orbb, 2018-05-05 19:10:35

How to properly upload images in Yii2?

Good afternoon!
I’m already building 3 sites on Yii, I’ve already successfully dug some of the functionality into components and don’t duplicate it, but the trouble is with the pictures.
Now I do this:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $currentData = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $image = UploadedFile::getInstance($model, 'image_name');
            if ($image != null) {
                if ($currentData->image_name)
                    ImagesController::deleteImage($currentData->image_name);
                $model->image_name = ImagesController::saveImage($image);
            } else {
                $model->image_name = $currentData->image_name;
            }
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

Who is too lazy to read the code:
I get the data, take the model before saving, check if there is a photo in the input file, if there is - I check for the old one, delete the old one, upload the new one, if not, but there is already a photo in the database - I put the old one in place models to save and fill back.
Transferred all responsibility for saving and deleting to a separate class, but you still have to duplicate such code in all models. Because firstly, the image disappears during Update (I didn’t make a hidden input), and secondly, before updating, I get the old data that is already in the model (can be replaced with clone - the essence will not change). I consider all this to be a clumsy implementation, because I constantly copy this code everywhere (well, if there is 1 model with a picture, but if there are 10 of them?)
How to centrally get rid of all this and stop such perversions? Component? Implement a separate route for images?
Tell me please :3

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question