首頁  >  文章  >  php框架  >  使用Yii框架創建電影網站

使用Yii框架創建電影網站

WBOY
WBOY原創
2023-06-21 09:04:321322瀏覽

隨著網路的普及以及人們對電影的熱愛,電影網站成為了一個受歡迎的網站類型。在創建一個電影網站時,一個好的框架是非常必要的。 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' => $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
  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' => 'ID',
            'title' => 'Title',
            'director' => 'Director',
            'actors' => 'Actors',
            'year' => 'Year',
            'genre' => 'Genre',
            'rating' => '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->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方法將刪除影片。

  1. 建立電影視圖

接下來,我們需要建立視圖檔案來顯示電影清單、新增影片和編輯影片的表單。將視圖檔案儲存在views/movie目錄中。

  • index.php - 用於顯示影片清單
<?php

use 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 - 用於建立新的影片
<?php

use 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 - 用於編輯​​電影
<?php

use 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>
  1. 運行電影網站

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

php yii serve

這將啟動一個本地Web伺服器,並在連接埠8000上執行你的應用程式。現在,你可以在瀏覽器中開啟http://localhost:8000/,看到你的電影網站了。

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

以上是使用Yii框架創建電影網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn