Home >PHP Framework >YII >Create a news website using Yii framework
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:
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.
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.
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:
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 news
Table, 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 news
sheet. 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
路由到NewsController
的Index
操作。
要定义路由和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
路由到NewsController
的Index
操作,而将news/create
路由到NewsController
的Create
操作。
第六步,测试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!