service = $service; $this->posts = $posts; $this->categories = $categories; $this->tags = $tags; } public function behaviors(): array { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['index', 'category', 'tag', 'post'], 'allow' => true, //'roles' => ['Blog'], ], [ 'actions' => ['comment'], 'allow' => true, 'roles' => ['Comments'], ], [ // all the action are accessible to admin 'allow' => true, 'roles' => ['admin'], ], ], ], ]; } /** * @return string */ public function actionIndex() { /* @var $dataProvider ActiveDataProvider */ $dataProvider = $this->posts->getAll(); $dataProvider->pagination->pageSize = 10; return $this->render('index', [ 'dataProvider' => $dataProvider, ]); } /** * @param $id * * @return string * @throws NotFoundHttpException */ public function actionCategory($id) { if (!$category = $this->categories->find($id)) { throw new NotFoundHttpException('The requested page does not exist.'); } $dataProvider = $this->posts->getAllByCategory($category); return $this->render('category', [ 'category' => $category, 'dataProvider' => $dataProvider, ]); } /** * @param $id * @return mixed * @throws NotFoundHttpException */ public function actionTag($id) { if (!$tag = $this->tags->find($id)) { throw new NotFoundHttpException('The requested page does not exist.'); } $dataProvider = $this->posts->getAllByTag($tag); return $this->render('tag', [ 'tag' => $tag, 'dataProvider' => $dataProvider, ]); } /** * @param $id * @return mixed * @throws NotFoundHttpException */ public function actionPost($id) { if (!$post = $this->posts->find($id)) { throw new NotFoundHttpException('The requested page does not exist.'); } return $this->render('post', [ 'post' => $post, ]); } /** * @param $id * @return mixed * @throws NotFoundHttpException */ public function actionComment($id) { if (!$post = $this->posts->find($id)) { throw new NotFoundHttpException('The requested page does not exist.'); } $form = new BlogCommentForm(); if ($form->load(Yii::$app->request->post()) && $form->validate()) { try { $comment = $this->service->create($post->id, Yii::$app->user->id, $form); return $this->redirect(['post', 'id' => $post->id, '#' => 'comment_' . $comment->id]); } catch (\DomainException $e) { Yii::$app->errorHandler->logException($e); Yii::$app->session->setFlash('error', $e->getMessage()); } } return $this->render('comment', [ 'post' => $post, 'model' => $form, ]); } }