search
HomePHP FrameworkYIICreate a movie website using Yii framework

With the popularity of the Internet and people's love for movies, movie websites have become a popular website type. When creating a movie website, a good framework is very necessary. Yii framework is a high-performance PHP framework that is easy to use and has excellent performance. In this article, we will explore how to create a movie website using the Yii framework.

  1. Install the Yii framework

Before using the Yii framework, you need to install the framework first. Installing the Yii framework is very simple, just execute the following command in the terminal:

composer create-project yiisoft/yii2-app-basic

This command will create a basic Yii2 application in the current directory. Now you are ready to start creating your movie website.

  1. Creating databases and tables

Yii framework provides ActiveRecord, a way to make operating databases easy. In this example, we will create a data table called movies, which contains information such as movie ID, title, director, actors, year, genre, and rating. To create the table, go to the application root directory in the terminal and run the following command:

php yii migrate/create create_movies_table

Then edit the generated migration file to the following content:

<?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}}');
    }
}

Now run the migration to create the movies data sheet.

php yii migrate
  1. Create movie model

In the Yii framework, it is very easy to define the model of the data table using ActiveRecord. We can create a model named Movie in the models directory and specify the table name and field name in the model definition.

<?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. Create Movie Controller

The movie controller will be responsible for handling all requests regarding movies, such as requests to add, edit, delete, and display movie lists. We can create a controller named MovieController in the controllers directory and add the following code:

<?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.');
    }
}

Among them, the actionIndex method will display the list of all movies, and the actionCreate and actionUpdate methods will be used to create and edit movies, The actionDelete method will delete the movie.

  1. Create a movie view

Next, we need to create a view file to display the movie list, add movie, and edit movie forms. Store view files in the views/movie directory.

  • index.php - used to display the list of movies
<?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 - used to create new movies
<?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 - for editing movies
<?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. Run the movie website

Now we have completed the creation of the Yii framework movie website, all The code is all ready. To run the movie website locally, go to the application root directory in the terminal and execute the following command:

php yii serve

This will start a local web server and run your application on port 8000. Now, you can open http://localhost:8000/ in your browser and see your movie website.

In this article, we have demonstrated how to create a movie website using Yii framework. Using the Yii framework will speed up your development and provide many useful features, such as ActiveRecord, MVC architecture, form validation, security, and more. To learn more about the Yii framework, check out its documentation.

The above is the detailed content of Create a movie website using Yii framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Yii Developers: Common ErrorsYii Developers: Common ErrorsMay 12, 2025 am 12:04 AM

ThemostcommonerrorsinYiiframeworkare"UnknownProperty","InvalidConfiguration","ClassNotFound",and"ValidationErrors".1."UnknownProperty"errorsoccurwhenaccessingnon-existentproperties;ensurepropertiesexi

Yii Developer: Most recquired skills in EuropeYii Developer: Most recquired skills in EuropeMay 11, 2025 am 12:02 AM

The key skills that European Yii developers need to possess include: 1. Yii framework proficiency, 2. PHP proficiency, 3. Database management, 4. Front-end skills, 5. RESTful API development, 6. Version control system, 7. Testing and debugging, 8. Security knowledge, 9. Agile methodology, 10. Soft skills, 11. Localization and internationalization, 12. Continuous learning, these skills make developers stand out in the European market.

Yii: Is the community still active?Yii: Is the community still active?May 10, 2025 am 12:03 AM

Yes,theYiicommunityisstillactiveandvibrant.1)TheofficialYiiforumremainsaresourcefordiscussionsandsupport.2)TheGitHubrepositoryshowsregularcommitsandpullrequests,indicatingongoingdevelopment.3)StackOverflowcontinuestohostYii-relatedquestionsandhigh-qu

Is it easy to migrate a Laravel Project to Yii?Is it easy to migrate a Laravel Project to Yii?May 09, 2025 am 12:01 AM

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

Essential Soft Skills for Yii Developers: Communication and CollaborationEssential Soft Skills for Yii Developers: Communication and CollaborationMay 08, 2025 am 12:11 AM

Soft skills are crucial to Yii developers because they facilitate team communication and collaboration. 1) Effective communication ensures that the project is progressing smoothly, such as through clear API documentation and regular meetings. 2) Collaborate to enhance team interaction through Yii's tools such as Gii to improve development efficiency.

Laravel MVC : What are the best benefits?Laravel MVC : What are the best benefits?May 07, 2025 pm 03:53 PM

Laravel'sMVCarchitectureoffersenhancedcodeorganization,improvedmaintainability,andarobustseparationofconcerns.1)Itkeepscodeorganized,makingnavigationandteamworkeasier.2)Itcompartmentalizestheapplication,simplifyingtroubleshootingandmaintenance.3)Itse

Yii: Is It Still Relevant in Modern Web Development?Yii: Is It Still Relevant in Modern Web Development?May 01, 2025 am 12:27 AM

Yiiremainsrelevantinmodernwebdevelopmentforprojectsneedingspeedandflexibility.1)Itoffershighperformance,idealforapplicationswherespeediscritical.2)Itsflexibilityallowsfortailoredapplicationstructures.However,ithasasmallercommunityandsteeperlearningcu

The Longevity of Yii: Reasons for Its EnduranceThe Longevity of Yii: Reasons for Its EnduranceApr 30, 2025 am 12:22 AM

Yii frameworks remain strong in many PHP frameworks because of their efficient, simplicity and scalable design concepts. 1) Yii improves development efficiency through "conventional optimization over configuration"; 2) Component-based architecture and powerful ORM system Gii enhances flexibility and development speed; 3) Performance optimization and continuous updates and iterations ensure its sustained competitiveness.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool