BlogPostsController.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use app\models\BlogPosts;
  5. use app\models\BlogPostsSearch;
  6. use yii\web\Controller;
  7. use yii\web\NotFoundHttpException;
  8. use yii\filters\VerbFilter;
  9. use yii\filters\AccessControl;
  10. use yii\web\UploadedFile;
  11. /**
  12. */
  13. class BlogPostsController extends Controller
  14. {
  15. public function behaviors()
  16. {
  17. return [
  18. 'verbs' => [
  19. 'class' => VerbFilter::className(),
  20. 'actions' => [
  21. 'delete' => ['POST'],
  22. ],
  23. ],
  24. 'access' =>[
  25. 'class' => AccessControl::className(),
  26. 'rules' => [
  27. [
  28. 'allow' => true,
  29. 'roles' => ['@'],
  30. ],
  31. ],
  32. ],
  33. ];
  34. }
  35. private function saveImg($model)
  36. {
  37. if($model->imageFile = UploadedFile::getInstance($model,'imageFile')){
  38. if($model->picture){
  39. @unlink($model->picture);
  40. }
  41. $imageName = 'uploads/'.$model->title . '.' . $model->imageFile->extension;
  42. $model->imageFile->saveAs($imageName );
  43. $model->picture = $imageName;
  44. $model->save(false);
  45. }
  46. }
  47. public function actionIndex()
  48. {
  49. $searchModel = new BlogPostsSearch();
  50. $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
  51. return $this->render('index', [
  52. 'searchModel' => $searchModel,
  53. 'dataProvider' => $dataProvider,
  54. ]);
  55. }
  56. public function actionView($id)
  57. {
  58. return $this->render('view', [
  59. 'model' => $this->findModel($id),
  60. ]);
  61. }
  62. public function actionCreate()
  63. {
  64. $model = new BlogPosts();
  65. $model->created_at = time();
  66. if ($model->load(Yii::$app->request->post()) && $model->upload()) {
  67. return $this->redirect(['view', 'id' => $model->id]);
  68. } else {
  69. return $this->render('create', [
  70. 'model' => $model,
  71. ]);
  72. }
  73. }
  74. public function actionUpdate($id)
  75. {
  76. $model = $this->findModel($id);
  77. if ($model->load(Yii::$app->request->post()) && $model->save()) {
  78. $this->saveImg($model);
  79. return $this->redirect(['view', 'id' => $model->id]);
  80. } else {
  81. return $this->render('update', [
  82. 'model' => $model,
  83. ]);
  84. }
  85. }
  86. public function actionDelete($id)
  87. {
  88. $this->findModel($id)->delete();
  89. return $this->redirect(['index']);
  90. }
  91. protected function findModel($id)
  92. {
  93. if (($model = BlogPosts::findOne($id)) !== null) {
  94. return $model;
  95. } else {
  96. throw new NotFoundHttpException('The requested page does not exist.');
  97. }
  98. }
  99. }