使用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 分享