2

I am making an application with Yii2 framework and I am not sure if I do everything right.

Here is an action from my controller:

public function actionView($id)
{
    $model = $this->findModel($id);
    $pictures = new Pictures();
    $upload = new UploadForm();
    $views = new Views();

    $contacts = $model->getContacts($model->user_id);
    $contact = $model->contact($model->user_id);

    $buttons = [
        'update' => '',
        'delete' => '',
    ];

    $gallery = '_gallery';
    $value = '';

    if (!Yii::$app->user->isGuest) {
        $isInBookmarks = Bookmark::find()->where([
            'user_id' => Yii::$app->user->identity->getId(), 'advert_id' => $id
        ])->all();

        if (!empty($isInBookmarks)) {
            $value = 'Delete ' . 'from bookmarks';
        } else {
            $value = 'Add to bookmarks';
        }

        if ($model->user_id == Yii::$app->user->identity->getId()) {
            $buttons['update'] = Html::a('Update advert', ['update', 'id' => $model->id], [
                'class' => 'btn btn-primary'
            ]);
            $buttons['delete'] = Html::a('Delete advert', ['delete', 'id' => $model->id], [
                'class' => 'btn btn-danger',
                'data' => [
                    'confirm' => 'Are you sure you want to delete this advert?',
                    'method' => 'post',
                ],
            ]);

            if (isset($_POST['delete_pic'])) {
                $model->deletePic();
            }

            $gallery = '_my-gallery';
        }
    }

    $views->countViews($_GET['id']);

    return $this->render('view', [
        'model' => $model,
        'contacts' =>$contacts,
        'contact' =>$contact,
        'value' => $value,
        'buttons' => $buttons,
        'pictures' => $pictures,
        'gallery' => $gallery,
        'upload' => $upload,
        'views' => $views,
    ]);
}

And here is my View code:

<div class="date-update">
    Last update: <?= date(Yii::$app->params['dateFormat'], $model->updated_at) ?>
</div>

<?= $this->render($gallery, [
   'pictures' => $pictures,
   'model' => $model,
   'upload' => $upload,
]) ?>

Is it correct to create

 $pictures = new Pictures();  

and

 $upload = new UploadForm();

in controller and to transmit them for two times to the view file, where I use them or I should better create them right in the view file? What will be right according to OOP and MVC principals?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Anastasia
  • 315
  • 1
  • 3
  • 13

1 Answers1

0

Why do you want to create them in the view file ?

The MVC logic is to only display things in the view file. You should never do anything else in the views.

If you have to interact with your Pictures object, how will you do it if you create the object in the view?

t-n-y
  • 1,201
  • 2
  • 13
  • 27