A
A
acv562016-06-17 19:38:33
Yii
acv56, 2016-06-17 19:38:33

How to move code from controller to model?

Hello. There is a controller in Yii2:

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

  if ($model->load(Yii::$app->request->post())) {
    $model->files 			= UploadedFile::getInstance($model, 'image');
      
    if ($model->validate()) {
    
      if ($model->files) {
        $name 			= $model->files->baseName . '.' . $model->files->extension;
        $path			= Yii::getAlias('@webroot' . '/uploads/') . $name;
        $model->files->saveAs($path);
        $model->image 	= $name;
          
        if($model->removeImage) {
          $fileRemove 	= Yii::getAlias('@webroot' . '/uploads/') . $image;
          if(file_exists($fileRemove)) {
            unlink($fileRemove);
            $model->image 	= '';
          }
        }
      }

      $model->save();
      return $this->redirect(['view', 'id' => $model->id]);		
    }
    
    
  } 
  
  else {
    return $this->render('update', [
      'model' 			=> $model,
    ]);
  }

}

Defined properties in the model:
public $files;
public $removeImage;

There are also rules, etc.
Everything works, but all my controllers are thick. I want to move the code to the model to make thin controllers. What parts of the code can be moved there and how to call it in the controller?
Whether it is necessary to transfer there from the controller such? :
Article::findOne($id)
Article::find()->where(['id' => $id])->all();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SharuPoNemnogu, 2016-06-17
@acv56

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', ['model' => $model]);
    }
}

leave this, everything else in the model in beforeSave()

N
Nikita, 2016-06-17
@bitver

We threw external data into the model, took data from it and passed it to the view. This will all take 4-5 lines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question