search
HomePHP FrameworkYIICreate a news website using Yii framework

Create a news website using Yii framework

Jun 21, 2023 am 08:40 AM
createyii frameworkNews website

With the popularity of online media, the demand for news websites is also growing. If you plan to create a news website, consider using the Yii framework to build your website. Yii is a popular PHP framework designed to make web application development simpler and more efficient.

Yii framework has many advantages, including:

  1. Efficient performance

Yii framework is a fast framework that is able to handle large amounts of Concurrent requests. This is because the Yii framework adopts some of the latest PHP technologies and uses a variety of caching mechanisms to improve website performance. This feature is very important for news websites as it needs to be able to handle high traffic situations.

  1. Flexible and easy to extend

The Yii framework is very flexible and can be easily extended and customized. If you need to add new functionality or modify existing functionality, the Yii framework provides very clear extension interfaces and class libraries. This means you can easily write new modules or plugins and integrate them into your website.

  1. High security

The Yii framework takes security as its design principle and provides a series of security protection mechanisms. These mechanisms include input filtering, data encryption, authentication, and authorization functions. These mechanisms are necessary to ensure that your news website is not vulnerable to hackers or other security threats.

Now, let’s take a look at how to create a news website using the Yii framework.

The first step is to install the Yii framework

Before you start, you need to install the Yii framework. There are two ways to install the Yii framework: through Composer or manual download. Here, I choose the Composer installation method. If you don't have Composer installed yet, please install Composer first and add it to your system path.

In the terminal, go to your project directory and run the following command to install the Yii framework:

composer require yiisoft/yii2-app-basic

This command will install the Yii Basic application template and Yii core library. After the installation is complete, you can execute the following command to run the Yii application:

./yii serve

This command will start a local web server and run your Yii application. You can open http://localhost:8080 in your browser to view your website homepage.

Second step, design your news website database

Before creating any web application, you need to design your database. Assume that our news website requires the following database table:

  • news: stores the title, content, date, author and other information of the news
  • category: stores the classification information of the news
  • user: Store user information for news websites

In the Yii framework, you can use the Migrations tool to create, update and manage your database. You can use the following command to create a new Migration:

./yii migrate/create create_news_table

This command will create a Migration class named create_news_table, which will be used to create the news table and other related tables (for example, category and user tables).

In the create_news_table class, you need to use the database API of the Yii framework to create your database table. For example, here is the sample code to create a news table:

<?php

use yiidbMigration;

class m210816_100000_create_news_table extends Migration
{
    public function safeUp()
    {
        $this->createTable('news', [
            'id' => $this->primaryKey(),
            'title' => $this->string()->notNull(),
            'content' => $this->text(),
            'category_id' => $this->integer(),
            'user_id' => $this->integer(),
            'created_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
        ]);

        $this->addForeignKey('fk_news_category', 'news', 'category_id', 'category', 'id', 'CASCADE', 'CASCADE');
        $this->addForeignKey('fk_news_user', 'news', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');
    }

    public function safeDown()
    {
        $this->dropForeignKey('fk_news_category', 'news');
        $this->dropForeignKey('fk_news_user', 'news');

        $this->dropTable('news');
    }
}

In this code, we use the createTable method of the Yii framework to create newsTable, then use the addForeignKey method to define foreign key constraints to ensure data consistency.

With the Migration class, you can use the following command to run Migration to create a new database table:

./yii migrate/up

This command will create a new database table and other related tables.

The third step is to create the Yii model

In the Yii framework, the model is the core part used to represent business logic and data, and is also part of the MVC architecture pattern. In the Yii framework, models are the simplest and most powerful way to process data.

To create a model, you can use the following command:

./yii generate/model News --tableName=news

This command will create a model named News and associate it to newssheet. Next, you need to customize your model using the following code:

<?php

namespace appmodels;

use Yii;

class News extends yiidbActiveRecord
{
    public static function tableName()
    {
        return 'news';
    }

    public function rules()
    {
        return [
            [['title'], 'required'],
            [['content'], 'string'],
            [['category_id', 'user_id'], 'integer'],
            [['created_at'], 'safe'],
            [['title'], 'string', 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'content' => 'Content',
            'category_id' => 'Category ID',
            'user_id' => 'User ID',
            'created_at' => 'Created At',
        ];
    }
}

In this code, we define the table name and validation rules for the News model, and also define the Label (text used to display to the user). You can access and modify data tables through this model, for example:

$news = new News();
$news->title = 'Hello, World!';
$news->content = 'Welcome to my news website.';
$news->category_id = 1;
$news->user_id = 1;
$news->save();

This will add a news item to the news table.

The fourth step is to create Yii controllers and views

In the Yii framework, the controller is the part used to process user requests and render responses. The controller routes user requests to the correct action and uses a specific view file to render the response.

To create a controller, you can use the following command:

./yii generate/controller News

This will create a controller named NewsController. Next, you need to add some operations to the controller, for example:

<?php

namespace appcontrollers;

use Yii;
use appmodelsNews;
use yiiwebController;

class NewsController extends Controller
{
    public function actionIndex()
    {
        $news = News::find()->all();
        return $this->render('index', [
            'news' => $news,
        ]);
    }

    public function actionView($id)
    {
        $news = News::findOne($id);
        return $this->render('view', [
            'news' => $news,
        ]);
    }

    public function actionCreate()
    {
        $news = new News();
        if ($news->load(Yii::$app->request->post()) && $news->save()) {
            return $this->redirect(['view', 'id' => $news->id]);
        }
        return $this->render('create', [
            'news' => $news,
        ]);
    }

    public function actionUpdate($id)
    {
        $news = News::findOne($id);
        if ($news->load(Yii::$app->request->post()) && $news->save()) {
            return $this->redirect(['view', 'id' => $news->id]);
        }
        return $this->render('update', [
            'news' => $news,
        ]);
    }

    public function actionDelete($id)
    {
        $news = News::findOne($id);
        $news->delete();
        return $this->redirect(['index']);
    }
}

In this code, we define five operations: Index, View, Create, Update and Delete. This presents the view file to the user and returns a response based on the user's request.

In order to create view files for these operations, for example:

  • app/views/news/index.php
  • app/views/news/view.php
  • app/views/news/create.php
  • app/views/news/update.php

你需要添加如下代码:

<?php foreach ($news as $item): ?>
    <div>
        <h2><?= $item->title ?></h2>
        <p><?= $item->content ?></p>
        <p><?= $item->created_at ?></p>
        <p>Author: <?= $item->user_id ?></p>
        <p>Category: <?= $item->category_id ?></p>
        <a href="<?= Yii::$app->urlManager->createUrl(['news/view', 'id' => $item->id]) ?>">View</a>
        <a href="<?= Yii::$app->urlManager->createUrl(['news/update', 'id' => $item->id]) ?>">Update</a>
        <a href="<?= Yii::$app->urlManager->createUrl(['news/delete', 'id' => $item->id]) ?>">Delete</a>
    </div>
<?php endforeach; ?>

在这个代码中,我们用循环遍历新闻,然后为每个新闻输出标题、内容、日期、作者和分类,以及三个按钮View、Update和Delete。

第五步,定义Yii路由和URL规则

在Yii框架中,路由和URL规则告诉Yii框架如何将用户请求路由到正确的控制器和操作。

默认情况下,Yii框架使用/controller/action格式的URL,例如/news/index。但是你可以自定义路由和URL规则,例如将/news路由到NewsControllerIndex操作。

要定义路由和URL规则,你可以使用如下代码:

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        // NewsController
        ['class' => 'yiiestUrlRule', 'controller' => 'news'],
        'news' => 'news/index',
        'news/create' => 'news/create',
        'news/<id:d+>' => 'news/view',
        'news/<id:d+>/update' => 'news/update',
        'news/<id:d+>/delete' => 'news/delete',
    ],
],

在这个代码中,我们使用规则数组来自定义路由和URL规则。例如,我们将news路由到NewsControllerIndex操作,而将news/create路由到NewsControllerCreate操作。

第六步,测试Yii应用程序

现在,你已经创建了一个新闻网站,并使用Yii框架构建了它。要测试你的新闻网站,你可以在终端中运行如下命令启动本地Web服务器:

./yii serve

然后在浏览器中打开http://localhost:8080,查看你的新闻网站。

最后,当你为你的新闻网站添加更多功能时,你可以根据你的业务需要扩展Yii框架的功能。Yii框架提供了许多工具和类库,可以帮助你尽可能快地开发出高效、安全和易于扩展的Web应用程序。

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

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools