Home  >  Article  >  PHP Framework  >  Create a Q&A website using Yii framework

Create a Q&A website using Yii framework

WBOY
WBOYOriginal
2023-06-21 09:36:021195browse

Yii framework is a powerful PHP framework that can help developers quickly build high-performance, scalable web applications. This article will introduce how to use the Yii framework to create a Q&A website.

  1. Environment preparation

Before starting, we need to ensure that necessary software and tools such as PHP and MySQL have been correctly configured in the local development environment. At the same time, we also need to install the Yii framework to facilitate subsequent development work.

Installing the Yii framework is very simple, just execute the following command:

composer create-project yiisoft/yii2-app-basic <project_name>

where 4fc59f85b86f3cdcf539b23b3b2209e3 is the name of the current project.

  1. Database design

Before creating a Q&A website, we need to design the relevant database structure. In this article, we will use the following database tables:

  • user: used to store user information, including user name, password, email, etc.;
  • question: used to store questions Information, including question title, content, release time, etc.;
  • answer: used to store answer information, including answer content, answer time, etc.

Here we use MySQL as the back-end database, and create the corresponding database and table through the following commands:

CREATE DATABASE IF NOT EXISTS my_db;
USE my_db;

CREATE TABLE IF NOT EXISTS `user` (
  `id` INT UNSIGNED AUTO_INCREMENT,
  `username` VARCHAR(64) NOT NULL,
  `password` VARCHAR(64) NOT NULL,
  `email` VARCHAR(64) NOT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `question` (
  `id` INT UNSIGNED AUTO_INCREMENT,
  `title` VARCHAR(255) NOT NULL,
  `content` TEXT,
  `user_id` INT UNSIGNED NOT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`user_id`) REFERENCES user(`id`)
);

CREATE TABLE IF NOT EXISTS `answer` (
  `id` INT UNSIGNED AUTO_INCREMENT,
  `content` TEXT,
  `question_id` INT UNSIGNED NOT NULL,
  `user_id` INT UNSIGNED NOT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`question_id`) REFERENCES question(`id`),
  FOREIGN KEY (`user_id`) REFERENCES user(`id`)
);

Note that we have set foreign keys in the table to associate different data sheet.

  1. Create a model

In the Yii framework, models are the most commonly used tools for operating databases. We need to create corresponding model files to operate the database tables created previously.

In the models folder under the application root directory, we create three model files User.php, Question.php,Answer.php. Taking User.php as an example, the code is as follows:

<?php
namespace appmodels;

use yiidbActiveRecord;

class User extends ActiveRecord
{
    public function rules()
    {
        return [
            [['username', 'password', 'email'], 'required'],
            ['email', 'email'],
            ['username', 'unique'],
        ];
    }

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

    public function validatePassword($password)
    {
        return $this->password === md5($password);
    }

    public function getQuestions()
    {
        return $this->hasMany(Question::className(), ['user_id' => 'id']);
    }

    public function getAnswers()
    {
        return $this->hasMany(Answer::className(), ['user_id' => 'id']);
    }
}

In this file, we define the attributes of the model, validation rules, query methods and relationships, etc.

  1. Creating Controllers

Controllers are tools used to handle routing and responding to requests. In the controllers folder under the application root directory, we create three controller files SiteController.php, QuestionController.php, AnswerController.php . Taking SiteController.php as an example, the code is as follows:

<?php
namespace appcontrollers;

use yiiwebController;

class SiteController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
}

In this file, we define a method named actionIndex for rendering the homepage template.

  1. Create a view

The view is the user interface part of the application. We need to create the corresponding view file to render the content. In the views folder under the application root directory, we create three folders site, question, answer, corresponding to the previous Create three controllers.

In the views/site folder, we create a file named index.php for rendering the homepage template. The code is as follows:

<h1>Welcome to the Question & Answer website!</h1>

In the views/question folder, we create a file named index.php for rendering the question list page. The code is as follows:

<h1>Questions</h1>

<?php foreach ($questions as $question): ?>
  <div>
    <h2><?= $question->title ?></h2>
    <p><?= $question->content ?></p>
  </div>
<?php endforeach; ?>

In the views/answer folder, we create a file named create.php for rendering the answer editing page. The code is as follows:

<h1>Create Answer</h1>

<?= $this->render('_form', ['model' => $model]) ?>
  1. Create routing

In the Yii framework, routing is used to map URL addresses to corresponding controllers and methods. We need to create the corresponding routing rules in the web.php file in the config folder in the application root directory. The code is as follows:

return [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '' => 'site/index',
                'question' => 'question/index',
                'answer/create/<question_id:d+>' => 'answer/create',
            ],
        ],
    ],
];

Note that we used the dynamic parameter question_id in the answer/create route. This parameter will be used when creating the answer.

  1. Create an authorization system

In the Q&A website, users need to log in to ask and answer questions. We need to create a basic authorization system to implement user login and registration functions.

In SiteController.php, we added two methods actionLogin and actionSignup for rendering login and registration pages. In UserController.php, we added a method named actionCreate to handle user registration requests. The specific code implementation is omitted.

  1. Implementing the Q&A function

In the Q&A website, users need to ask and answer questions. We need to create relevant functions to implement these two operations.

In QuestionController.php, we added two methods actionIndex and actionCreate for rendering the question list and question editing page. In QuestionController.php, we created a method named actionCreate to handle question creation requests. The specific code implementation is omitted.

In AnswerController.php, we created a method named actionCreate to handle the answer creation request. The specific code implementation is omitted.

  1. Test

After the above development work, we have completed a basic Q&A website. We can open the homepage by visiting http://localhost/4fc59f85b86f3cdcf539b23b3b2209e3, and open the question list by visiting http://localhost/4fc59f85b86f3cdcf539b23b3b2209e3/question. We can also ask and answer questions through registered users.

The above is the detailed content of Create a Q&A 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