使用Yii框架创建电影网站

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

使用Yii框架创建电影网站

随着互联网的普及以及人们对电影的热爱,电影网站成为了一个受欢迎的网站类型。在创建一个电影网站时,一个好的框架是非常必要的。Yii框架是一个高性能的PHP框架,易于使用且具有出色的性能。在本文中,我们将探讨如何使用Yii框架创建一个电影网站。

安装Yii框架

在使用Yii框架之前,需要先安装框架。安装Yii框架非常简单,只需要在终端执行以下命令:

composer create-project yiisoft/yii2-app-basic
登录后复制

该命令将在当前目录中创建一个基本的Yii2应用程序。现在你已经准备好开始创建你的电影网站了。

创建数据库和表格

Yii框架提供了ActiveRecord,这是一种使操作数据库变得容易的方式。在本例中,我们将创建一个名为movies的数据表,该表包含电影ID、标题、导演、演员、年份、类型和评分等信息。要创建表,请在终端中进入应用程序根目录,然后运行以下命令:

php yii migrate/create create_movies_table
登录后复制

然后将生成的迁移文件编辑为以下内容:

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

现在运行迁移以创建movies数据表。

php yii migrate
登录后复制创建电影模型

在Yii框架中,使用ActiveRecord非常容易定义数据表的模型。我们可以在models目录下创建一个名为Movie的模型,并在模型定义中指定表格名和字段名。

<?phpnamespace 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' => 'ID',            'title' => 'Title',            'director' => 'Director',            'actors' => 'Actors',            'year' => 'Year',            'genre' => 'Genre',            'rating' => 'Rating'        ];    }}
登录后复制创建电影控制器

电影控制器将负责处理有关电影的所有请求,例如添加、编辑、删除和显示电影列表等请求。我们可以在controllers目录下创建一个名为MovieController的控制器,并添加以下代码:

<?phpnamespace 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->render('index', ['movies' => $movies]);    }    /**     * Creates a new movie.     *     * @return string|yiiwebResponse     */    public function actionCreate()    {        $model = new Movie();        if ($model->load(Yii::$app->request->post()) && $model->save()) {            return $this->redirect(['index']);        }        return $this->render('create', [            'model' => $model,        ]);    }    /**     * Updates an existing movie.     *     * @param integer $id     * @return string|yiiwebResponse     * @throws yiiwebNotFoundHttpException     */    public function actionUpdate($id)    {        $model = $this->findModel($id);        if ($model->load(Yii::$app->request->post()) && $model->save()) {            return $this->redirect(['index']);        }        return $this->render('update', [            'model' => $model,        ]);    }    /**     * Deletes an existing movie.     *     * @param integer $id     * @return yiiwebResponse     * @throws yiiwebNotFoundHttpException     */    public function actionDelete($id)    {        $this->findModel($id)->delete();        return $this->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方法将删除电影。

创建电影视图

接下来,我们需要创建视图文件来显示电影列表、添加电影和编辑电影的表单。将视图文件存储在views/movie目录中。

index.php - 用于显示电影列表
<?phpuse yiihelpersHtml;use yiigridGridView;/* @var $this yiiwebView *//* @var $movies appmodelsMovie[] */$this->title = 'Movies';$this->params['breadcrumbs'][] = $this->title;?><h1><?= Html::encode($this->title) ?></h1><p>    <?= Html::a('Create Movie', ['create'], ['class' => 'btn btn-success']) ?></p><?= GridView::widget([    'dataProvider' => new yiidataArrayDataProvider([        'allModels' => $movies,        'sort' => [            'attributes' => [                'title',                'director',                'year',                'genre',                'rating',            ],        ],    ]),    'columns' => [        ['class' => 'yiigridSerialColumn'],        'title',        'director',        'actors:ntext',        'year',        'genre',        'rating',        ['class' => 'yiigridActionColumn'],    ],]); ?>
登录后复制create.php - 用于创建新的电影
<?phpuse yiihelpersHtml;use yiiwidgetsActiveForm;/* @var $this yiiwebView *//* @var $model appmodelsMovie */$this->title = 'Create Movie';$this->params['breadcrumbs'][] = ['label' => 'Movies', 'url' => ['index']];$this->params['breadcrumbs'][] = $this->title;?><h1><?= Html::encode($this->title) ?></h1><div class="movie-form">    <?php $form = ActiveForm::begin(); ?>    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'director')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'actors')->textarea(['rows' => 6]) ?>    <?= $form->field($model, 'year')->textInput() ?>    <?= $form->field($model, 'genre')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'rating')->textInput() ?>    <div class="form-group">        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>    </div>    <?php ActiveForm::end(); ?></div>
登录后复制update.php - 用于编辑电影
<?phpuse yiihelpersHtml;use yiiwidgetsActiveForm;/* @var $this yiiwebView *//* @var $model appmodelsMovie */$this->title = 'Update Movie: ' . $model->title;$this->params['breadcrumbs'][] = ['label' => 'Movies', 'url' => ['index']];$this->params['breadcrumbs'][] = ['label' => $model->title, 'url' => ['view', 'id' => $model->id]];$this->params['breadcrumbs'][] = 'Update';?><h1><?= Html::encode($this->title) ?></h1><div class="movie-form">    <?php $form = ActiveForm::begin(); ?>    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'director')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'actors')->textarea(['rows' => 6]) ?>    <?= $form->field($model, 'year')->textInput() ?>    <?= $form->field($model, 'genre')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'rating')->textInput() ?>    <div class="form-group">        <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>    </div>    <?php ActiveForm::end(); ?></div>
登录后复制运行电影网站

现在我们已经完成了Yii框架电影网站的创建,所有代码都已经就绪。要在本地运行电影网站,请在终端中进入应用程序根目录,然后执行以下命令:

php yii serve
登录后复制

这将启动一个本地Web服务器,并在端口8000上运行你的应用程序。现在,你可以在浏览器中打开http://localhost:8000/,看到你的电影网站了。

在这篇文章中,我们已经演示了如何使用Yii框架创建电影网站。使用Yii框架会加快你的开发速度,并提供很多有用的特性,例如ActiveRecord、MVC架构、表单验证、安全性等等。要深入了解Yii框架,请查看其文档。

以上就是使用Yii框架创建电影网站的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。
作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:workerman+thinkphp制作简易聊天室
下一篇:聊聊小程序与App间怎么进行跳转

发表评论

关闭广告
关闭广告