使用Yii框架創建電影網站

隨著互聯網的普及以及人們對電影的熱愛,電影網站成為了一個受歡迎的網站類型。在創建一個電影網站時,一個好的框架是非常必要的。YII框架是一個高性能的php框架,易于使用且具有出色的性能。在本文中,我們將探討如何使用yii框架創建一個電影網站。

  1. 安裝Yii框架

在使用Yii框架之前,需要先安裝框架。安裝Yii框架非常簡單,只需要在終端執行以下命令:

composer create-project yiisoft/yii2-app-basic

該命令將在當前目錄中創建一個基本的Yii2應用程序。現在你已經準備好開始創建你的電影網站了。

  1. 創建數據庫和表格

Yii框架提供了ActiveRecord,這是一種使操作數據庫變得容易的方式。在本例中,我們將創建一個名為movies的數據表,該表包含電影ID、標題、導演、演員、年份、類型和評分等信息。要創建表,請在終端中進入應用程序根目錄,然后運行以下命令:

php yii migrate/create create_movies_table

然后將生成的遷移文件編輯為以下內容:

<?php use yiidbMigration;  /**  * Handles the creation of table `{{%movies}}`.  */ class m210630_050401_create_movies_table extends Migration {     /**      * {@inheritdoc}      */     public function safeUp()     {         $this->createTable('{{%movies}}', [             'id' =&gt; $this-&gt;primaryKey(),             'title' =&gt; $this-&gt;string()-&gt;notNull(),             'director' =&gt; $this-&gt;string()-&gt;notNull(),             'actors' =&gt; $this-&gt;text()-&gt;notNull(),             'year' =&gt; $this-&gt;integer()-&gt;notNull(),             'genre' =&gt; $this-&gt;string()-&gt;notNull(),             'rating' =&gt; $this-&gt;decimal(3,1)-&gt;notNull(),         ]);     }      /**      * {@inheritdoc}      */     public function safeDown()     {         $this-&gt;dropTable('{{%movies}}');     } }

現在運行遷移以創建movies數據表。

php yii migrate
  1. 創建電影模型

在Yii框架中,使用ActiveRecord非常容易定義數據表的模型。我們可以在models目錄下創建一個名為Movie的模型,并在模型定義中指定表格名和字段名。

<?php namespace appmodels;  use yiidbActiveRecord;  class Movie extends ActiveRecord {     /**      * {@inheritdoc}      */     public static function tableName()     {         return '{{%movies}}';     }      /**      * {@inheritdoc}      */     public function rules()     {         return [             [['title', 'director', 'actors', 'year', 'genre', 'rating'], 'required'],             [['year'], 'integer'],             [['rating'], 'number'],             [['actors'], 'string'],             [['title', 'director', 'genre'], 'string', 'max' => 255],         ];     }      /**     * {@inheritdoc}     */     public function attributeLabels()     {         return [             'id' =&gt; 'ID',             'title' =&gt; 'Title',             'director' =&gt; 'Director',             'actors' =&gt; 'Actors',             'year' =&gt; 'Year',             'genre' =&gt; 'Genre',             'rating' =&gt; 'Rating'         ];     } }
  1. 創建電影控制器

電影控制器將負責處理有關電影的所有請求,例如添加、編輯、刪除和顯示電影列表等請求。我們可以在controllers目錄下創建一個名為MovieController的控制器,并添加以下代碼:

<?php namespace appcontrollers;  use Yii; use yiiwebController; use appmodelsMovie;  class MovieController extends Controller {     /**      * Shows all movies.      *      * @return string      */     public function actionIndex()     {         $movies = Movie::find()->all();         return $this-&gt;render('index', ['movies' =&gt; $movies]);     }      /**      * Creates a new movie.      *      * @return string|yiiwebResponse      */     public function actionCreate()     {         $model = new Movie();          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;save()) {             return $this-&gt;redirect(['index']);         }          return $this-&gt;render('create', [             'model' =&gt; $model,         ]);     }      /**      * Updates an existing movie.      *      * @param integer $id      * @return string|yiiwebResponse      * @throws yiiwebNotFoundhttpException      */     public function actionUpdate($id)     {         $model = $this-&gt;findModel($id);          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;save()) {             return $this-&gt;redirect(['index']);         }          return $this-&gt;render('update', [             'model' =&gt; $model,         ]);     }      /**      * Deletes an existing movie.      *      * @param integer $id      * @return yiiwebResponse      * @throws yiiwebNotFoundHttpException      */     public function actionDelete($id)     {         $this-&gt;findModel($id)-&gt;delete();          return $this-&gt;redirect(['index']);     }      /**      * Finds the Movie model based on its primary key value.      * If the model is not found, a 404 HTTP exception will be thrown.      *      * @param integer $id      * @return ppmodelsMovie      * @throws NotFoundHttpException if the model cannot be found      */     protected function findModel($id)     {         if (($model = Movie::findOne($id)) !== null) {             return $model;         }          throw new NotFoundHttpException('The requested page does not exist.');     } }

其中,actionIndex方法將顯示所有電影的列表,actionCreate和actionUpdate方法將用于創建和編輯電影,actionDelete方法將刪除電影。

  1. 創建電影視圖

接下來,我們需要創建視圖文件來顯示電影列表、添加電影和編輯電影的表單。將視圖文件存儲在views/movie目錄中。

  • index.php – 用于顯示電影列表
<?php use yiihelpersHtml; use yiigridGridView;  /* @var $this yiiwebView */ /* @var $movies appmodelsMovie[] */  $this->title = 'Movies'; $this-&gt;params['breadcrumbs'][] = $this-&gt;title; ?&gt;  <h1>= Html::encode($this-&gt;title) ?&gt;</h1>  <p>     = Html::a('Create Movie', ['create'], ['class' =&gt; 'btn btn-success']) ?&gt; </p>  = GridView::widget([     'dataProvider' =&gt; new yiidataArrayDataProvider([         'allModels' =&gt; $movies,         'sort' =&gt; [             'attributes' =&gt; [                 'title',                 'director',                 'year',                 'genre',                 'rating',             ],         ],     ]),     'columns' =&gt; [         ['class' =&gt; 'yiigridSerialColumn'],          'title',         'director',         'actors:ntext',         'year',         'genre',         'rating',          ['class' =&gt; 'yiigridActionColumn'],     ], ]); ?&gt;
  • create.php – 用于創建新的電影
<?php use yiihelpersHtml; use yiiwidgetsActiveForm;  /* @var $this yiiwebView */ /* @var $model appmodelsMovie */  $this->title = 'Create Movie'; $this-&gt;params['breadcrumbs'][] = ['label' =&gt; 'Movies', 'url' =&gt; ['index']]; $this-&gt;params['breadcrumbs'][] = $this-&gt;title; ?&gt; <h1>= Html::encode($this-&gt;title) ?&gt;</h1>  <div class="movie-form">      <?php $form = ActiveForm::begin(); ?>= $form-&gt;field($model, 'title')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'director')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'actors')-&gt;textarea(['rows' =&gt; 6]) ?&gt;      = $form-&gt;field($model, 'year')-&gt;textInput() ?&gt;      = $form-&gt;field($model, 'genre')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'rating')-&gt;textInput() ?&gt;      <div class="form-group">         = Html::submitButton('Save', ['class' =&gt; 'btn btn-success']) ?&gt;     </div>      <?php ActiveForm::end(); ?> </div>
  • update.php – 用于編輯電影
<?php use yiihelpersHtml; use yiiwidgetsActiveForm;  /* @var $this yiiwebView */ /* @var $model appmodelsMovie */  $this->title = 'Update Movie: ' . $model-&gt;title; $this-&gt;params['breadcrumbs'][] = ['label' =&gt; 'Movies', 'url' =&gt; ['index']]; $this-&gt;params['breadcrumbs'][] = ['label' =&gt; $model-&gt;title, 'url' =&gt; ['view', 'id' =&gt; $model-&gt;id]]; $this-&gt;params['breadcrumbs'][] = 'Update'; ?&gt; <h1>= Html::encode($this-&gt;title) ?&gt;</h1>  <div class="movie-form">      <?php $form = ActiveForm::begin(); ?>= $form-&gt;field($model, 'title')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'director')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'actors')-&gt;textarea(['rows' =&gt; 6]) ?&gt;      = $form-&gt;field($model, 'year')-&gt;textInput() ?&gt;      = $form-&gt;field($model, 'genre')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;      = $form-&gt;field($model, 'rating')-&gt;textInput() ?&gt;      <div class="form-group">         = Html::submitButton('Save', ['class' =&gt; 'btn btn-primary']) ?&gt;     </div>      <?php ActiveForm::end(); ?> </div>
  1. 運行電影網站

現在我們已經完成了Yii框架電影網站的創建,所有代碼都已經就緒。要在本地運行電影網站,請在終端中進入應用程序根目錄,然后執行以下命令:

php yii serve

這將啟動一個本地Web服務器,并在端口8000上運行你的應用程序。現在,你可以在瀏覽器中打開http://localhost:8000/,看到你的電影網站了。

在這篇文章中,我們已經演示了如何使用Yii框架創建電影網站。使用Yii框架會加快你的開發速度,并提供很多有用的特性,例如ActiveRecord、mvc架構表單驗證、安全性等等。要深入了解Yii框架,請查看其文檔。

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享