Home > PHP Framework > YII > body text

Create a wedding planning website using Yii framework

WBOY
Release: 2023-06-21 08:48:21
Original
1503 people have browsed it

Wedding is an important moment in everyone's life. For most people, a beautiful wedding is very important. When planning a wedding, the couple not only pays attention to the size and splendor of the wedding, but also pays more attention to the details and personalized experience of the wedding. To solve this problem, many wedding planning companies have established and developed their own websites. This article will introduce how to use the Yii framework to create a wedding planning website.

Yii framework is a high-performance PHP framework. Its simplicity and ease of use are deeply loved by developers. Using the Yii framework, we can develop a high-quality website more efficiently. The following will introduce how to use the Yii framework to create a wedding planning website.

Step 1: Install the Yii framework
First, we need to install the Yii framework. You can install it through composer:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic
Copy after login

or download the Yii framework compressed package and extract it to the server directory. After decompression, run the following command to install the required dependencies:

php composer.phar install
Copy after login

Step 2: Create the database and corresponding tables
In the previous step, we have successfully installed the Yii framework. Next, you need to create the database and corresponding tables. It can be created directly through tools such as MySQL Workbench.

Create a database named wedding, and then create a table with the following structure:

CREATE TABLE IF NOT EXISTS `user` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `username` VARCHAR(255) NOT NULL,
    `password_hash` VARCHAR(255) NOT NULL,
    `email` VARCHAR(255) NOT NULL,
    `auth_key` VARCHAR(255) NOT NULL,
    `status` SMALLINT NOT NULL DEFAULT 10,
    `created_at` INT NOT NULL,
    `updated_at` INT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `article` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `title` VARCHAR(255) NOT NULL,
    `content` TEXT NOT NULL,
    `status` SMALLINT NOT NULL DEFAULT 10,
    `created_at` INT NOT NULL,
    `updated_at` INT NOT NULL,
    `user_id` INT UNSIGNED NOT NULL,
    CONSTRAINT `fk_article_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

Among them, the user table stores user information, and the article table stores article information.

Step 3: Create the model
In the Yii framework, the model is part of the M (Model) in the MVC architecture and is responsible for processing data. We need to create two models, User and Article:

class User extends ActiveRecord implements IdentityInterface
{
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
}

class Article extends ActiveRecord
{
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
}
Copy after login

In the above code, we define two models, User and Article, by inheriting the ActiveRecord class. The User model implements the IdentityInterface interface for identity authentication; the Article model defines the relationship between users and articles through the getUser() method.

Step 4: Create controllers and views
In the Yii framework, the controller is part of the C (Controller) in the MVC architecture and is responsible for processing received web requests. We need to create two controllers: UserController and ArticleController, as well as corresponding views.

UserController is used to handle user registration, login and other operations:

class UserController extends Controller
{
    public function actionSignup()
    {
        $model = new SignupForm();

        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            Yii::$app->session->setFlash('success', 'Thank you for registration. Please check your inbox for verification email.');
            return $this->goHome();
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionLogin()
    {
        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}
Copy after login

ArticleController is used to handle article editing, display and other operations:

class ArticleController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create', 'update'],
                'rules' => [
                    [
                        'actions' => ['create', 'update'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Article::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new Article();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
Copy after login

In the above code, we use Some built-in components and operations of Yii, such as AccessControl, ActiveDataProvider, VerbFilter, etc., for more efficient development.

Step 5: Configure routing and database
In the Yii framework, routing configuration and database connection configuration need to be configured in the configuration file. We need to edit the following two files:

/config/web.php:

return [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            'csrfParam' => '_csrf',
        ],
        'user' => [
            'identityClass' => 'appmodelsUser',
            'enableAutoLogin' => true,
        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'wedding_session',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yiilogFileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '' => 'article/index',
                '<controller>/<action>' => '<controller>/<action>',
                '<controller>/<action>/<id:d+>' => '<controller>/<action>',
            ],
        ],
        'db' => require __DIR__ . '/db.php',
    ],
    'params' => $params,
];
Copy after login

In the above code, the database, URL routing and other information need to be configured so that the project can run smoothly. The database connection information needs to be configured in the /config/db.php file so that the Yii framework can interact with the database.

Finally, we also need to configure email sending information in /config/params.php so that users can receive verification emails after successful registration.

At this point, we have completed the entire process of creating a wedding planning website using the Yii framework. Through the introduction of this article, you have already understood the basic usage of Yii framework and how to create a simple wedding planning website. If you want to create a more complex and professional wedding website, you need to further learn the Yii framework to develop web applications more efficiently.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template