search
HomePHP FrameworkYIIHow to create hello page using yii framework

How to create hello page using yii framework

This chapter describes how to create a new “Hello” page in your application. To achieve this goal, an action and a view will be created:

The application will dispatch the page request to the action (Recommended learning: yii tutorial)

The action will in turn render the view presenting "Hello" to the end user

Throughout this chapter, you will learn three things:

How to create an action to respond to requests,

how to create a view to construct response content,

and how an application dispatches requests to actions.

Create action

For "Hello", you need to create a say action that receives the message parameter from the request and displays it to the end user. If the request does not provide a message parameter, the operation will display the default parameter "Hello".

信息: 操作是最终用户可以直接访问并执行的对象。 操作被组织在控制器中。 一个操作的执行结果就是最终用户收到的响应内容。

The operation must be declared in the controller. For simplicity, you can declare the say action directly in the SiteController controller. This controller is defined by the file controllers/SiteController.php. The following is the declaration of an action:

<?php

namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
    // ...现存的代码...

    public function actionSay($message = &#39;Hello&#39;)
    {
        return $this->render(&#39;say&#39;, [&#39;message&#39; => $message]);
    }
}

In the above SiteController code, the say action is defined as the actionSay method. Yii uses the action prefix to distinguish between ordinary methods and operations. The name following the action prefix is ​​mapped to the ID of the action.

When it comes to naming operations, you should understand how Yii handles operation IDs. Operation IDs are always treated in lowercase. If an operation ID consists of multiple words, the words will be connected by hyphens (such as create-comment).

When the operation ID is mapped to the method name, hyphens are removed, the first letter of each word is capitalized, and the action prefix is ​​added. Example: The action ID create-comment is equivalent to the method name actionCreateComment.

The operation method in the above code accepts a parameter $message, whose default value is "Hello" (just like you set the default value of other functions or methods in PHP). When the application receives the request and determines that the say operation will respond to the request, the application will find the corresponding value from the request parameters and pass it in.

In other words, if the request contains a message parameter and its value is "Goodbye", the $message variable in the action method will also be filled with "Goodbye".

In the operation method, render() is used to render a view file named say. The message parameter is also passed into the view so it can be used inside. The action method returns the rendering result. The results are received by the application and displayed to the end user's browser (as part of the full page HTML).

Creating Views

Views are scripts you use to generate response content. To say "Hello", you need to create a say view that displays the message parameter passed from the action method.

<?php
use yii\helpers\Html;
?>
<?= Html::encode($message) ?>

say views should be saved as views/site/say.php file. When the render() method is called in an operation, it will load the PHP file according to the views/controller ID/view name.php path.

Note that in the above code, the message parameter is processed by the HTML-encoded method before output. This is necessary because when the parameters come from the end user, malicious JavaScript code that may be hidden in the parameters can lead to cross-site scripting (XSS) attacks.

Of course, you will probably put more content in the say view. Content can consist of HTML tags, plain text, or even PHP statements. In fact, the say view is a PHP script executed by render(). The content output by the view script will be returned to the application as a response result. The application will in turn output the results to the end user.

Trial Run

After creating the action and view, you can access the new page through the following URL:

http://hostname/index.php?r=site/say&message=Hello+World

How to create hello page using yii framework

This URL will output a page containing "Hello World", using the same header and trailer as other pages in the application.

If you omit the message parameter in the URL, you will see that the page only displays "Hello". This is because message is passed as a parameter to the actionSay() method, and when it is omitted, the default "Hello" parameter will be used instead.

信息: 新页面和其它页面使用同样的头部和尾部是因为 render() 方法会自动把 say 视图执行的结果嵌入称为布局的文件中, 本例中是 views/layouts/main.php。

The parameter r in the URL above needs more explanation. It represents a route, which is an independent ID at the entire application level that points to a specific operation. The routing format is controller ID/operation ID. When the application accepts a request, it checks the parameters and uses the controller ID to determine which controller should be used to handle the request. The corresponding controller will then use the action ID to determine which action method will be used to do the specific work.

In the above example, the route site/say will be parsed to the SiteController controller and the say operation therein. Therefore the SiteController::actionSay() method will be called to handle the request.

信息: 与操作一样,一个应用中控制器同样有唯一的 ID。 控制器 ID 和操作 ID 使用同样的命名规则。 控制器的类名源自于控制器 ID, 移除了连字符,每个单词首字母大写,并加上 Controller 后缀。 例子:控制器 ID post-comment 相当于控制器类名 PostCommentController

The above is the detailed content of How to create hello page 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's Continued Use: Examining Its Current StatusYii's Continued Use: Examining Its Current StatusApr 17, 2025 am 12:09 AM

Yii is still competitive in modern development. 1) High performance: adopts lazy loading and caching mechanisms. 2) Security: Built-in CSRF and SQL injection protection. 3) Extensibility: Component-based design is easy to expand and customize.

Yii's Community: Support and ResourcesYii's Community: Support and ResourcesApr 16, 2025 am 12:04 AM

The Yii community provides rich support and resources. 1. Visit the official website and GitHub to get the documentation and code. 2. Use official forums and StackOverflow to solve technical problems. 3. Report bugs and make suggestions through GitHubIssues. 4. Use documents and tutorials to learn the Yii framework.

Yii: A Strong Framework for Web DevelopmentYii: A Strong Framework for Web DevelopmentApr 15, 2025 am 12:09 AM

Yii is a high-performance PHP framework designed for fast development and efficient code generation. Its core features include: MVC architecture: Yii adopts MVC architecture to help developers separate application logic and make the code easier to maintain and expand. Componentization and code generation: Through componentization and code generation, Yii reduces the repetitive work of developers and improves development efficiency. Performance Optimization: Yii uses latency loading and caching technologies to ensure efficient operation under high loads and provides powerful ORM capabilities to simplify database operations.

Yii: The Rapid Development FrameworkYii: The Rapid Development FrameworkApr 14, 2025 am 12:09 AM

Yii is a high-performance framework based on PHP, suitable for rapid development of web applications. 1) It adopts MVC architecture and component design to simplify the development process. 2) Yii provides rich functions, such as ActiveRecord, RESTfulAPI, etc., which supports high concurrency and expansion. 3) Using Gii tools can quickly generate CRUD code and improve development efficiency. 4) During debugging, you can check configuration files, use debugging tools and view logs. 5) Performance optimization suggestions include using cache, optimizing database queries and maintaining code readability.

The Current State of Yii: A Look at Its PopularityThe Current State of Yii: A Look at Its PopularityApr 13, 2025 am 12:19 AM

YiiremainspopularbutislessfavoredthanLaravel,withabout14kGitHubstars.ItexcelsinperformanceandActiveRecord,buthasasteeperlearningcurveandasmallerecosystem.It'sidealfordevelopersprioritizingefficiencyoveravastecosystem.

Yii: Key Features and Advantages ExplainedYii: Key Features and Advantages ExplainedApr 12, 2025 am 12:15 AM

Yii is a high-performance PHP framework that is unique in its componentized architecture, powerful ORM and excellent security. 1. The component-based architecture allows developers to flexibly assemble functions. 2. Powerful ORM simplifies data operation. 3. Built-in multiple security functions to ensure application security.

Yii's Architecture: MVC and MoreYii's Architecture: MVC and MoreApr 11, 2025 pm 02:41 PM

Yii framework adopts an MVC architecture and enhances its flexibility and scalability through components, modules, etc. 1) The MVC mode divides the application logic into model, view and controller. 2) Yii's MVC implementation uses action refinement request processing. 3) Yii supports modular development and improves code organization and management. 4) Use cache and database query optimization to improve performance.

Yii 2.0 Deep Dive: Performance Tuning & OptimizationYii 2.0 Deep Dive: Performance Tuning & OptimizationApr 10, 2025 am 09:43 AM

Strategies to improve Yii2.0 application performance include: 1. Database query optimization, using QueryBuilder and ActiveRecord to select specific fields and limit result sets; 2. Caching strategy, rational use of data, query and page cache; 3. Code-level optimization, reducing object creation and using efficient algorithms. Through these methods, the performance of Yii2.0 applications can be significantly improved.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool