search
Homephp教程PHP开发Quick Start with Yii (2)
Quick Start with Yii (2)Dec 20, 2016 am 11:08 AM

3. Controller (Controller)
Controller is an instance of a subclass of the CController class. It is created by the application when requested by the user. When a controller runs, it performs the requested action (controller class method), which typically introduces the necessary model and renders the corresponding view. An action is a controller class method whose name starts with action (action + the action name with a capital letter).
Controller class files are saved in protected/controllers/
Controllers and actions are identified by ID.
The controller ID is in the format of 'parent directory/subdirectory/controller name', corresponding to the corresponding controller class file protected/controllers/parent directory/subdirectory/controller name with capital initials Controller.php;
The action ID is the action method name minus the action prefix.
1. Routing
Users request specific controllers and actions in the form of routing. Routes are connected by a controller ID and an action ID, separated by a slash.
For example, the route post/edit represents the PostController and its edit

Action. By default, the URL http://hostname/index.php?r=post/edit requests this controller and action.
Note: By default, routes are case-sensitive. You can make routing case-insensitive by setting CUrlManager::caseSensitive in the application configuration to false. When in case-insensitive mode, make sure you follow the convention that directory names containing controller class files are lowercase, and that keys used in controller maps and action maps are lowercase.
The format of routing: controller ID/action ID or module ID/controller ID/action ID (if it is a nested module, the module ID is the parent module ID/submodule ID)
2. Controller instantiation
The application will use The following rules determine the controller class and the location of the class file:
1. If CWebApplication::catchAllRequest is specified, the controller will be created based on this attribute, and the user-specified controller ID will be ignored. This is typically used to put the application into maintenance state and display a static prompt page.
2. If the ID is found in CWebApplication::controllerMap, the corresponding controller configuration will be used to create the controller instance.
3. If the ID is in the format of 'path/to/xyz', the name of the controller class will be judged to be XyzController, and the corresponding class file will be protected/controllers/path/to/XyzController.php. If the class file does not exist, a 404CHttpException will be triggered.
In the case of using modules, the application will check if this ID represents a controller in a module. If so, the module instance will be created first, and then the controller instances within the module will be created.
3. Action
Action is defined as a method named with the word action as the prefix. A more advanced way is to define an action class and have the controller instantiate it when a request is received. This allows actions to be reused, improving reusability.
1. Define an action class. The basic format is as follows:
class UpdateAction extends CAction
{
public function run()
{
// place the action logic here
}
}
2. Use action classes: In order to make the controller pay attention To get to this action, we need to override the actions() method of the controller class in the following way:
class PostController extends CController
{
public function actions()
{
return array(
'edit'=>'application.controllers.post .UpdateAction',//Use the classes in the "Application Folder/controllers/post/UpdateAction.php" file to handle the edit action
);
}
}
As shown above, we used the path alias "application.controllers .post.UpdateAction" specifies the action class file as "protected/controllers/post/UpdateAction.php".
By writing class-based actions, we can organize the application into a module style. For example, the following directory structure can be used to organize controller related code:
protected/
controllers/
PostController.php
UserController.php
post/
CreateAction.php
ReadAction.php
UpdateAction.php
user/
CreateAction.php
ListAction.php
ProfileAction.php
UpdateAction.php
4. Filter
A filter is a piece of code that can be configured to be executed before or after the controller action is executed.
An action can have multiple filters. If there are multiple filters, they are executed in the order they appear in the filter list. Filters can prevent actions and other subsequent filters from executing.
Filters can be defined as methods of a controller class. Filter method names must start with filter. For example, the existing filterAccessControl method defines a filter named accessControl. The filter method must have the following structure:
public function filterAccessControl($filterChain)
{
// Call $filterChain->run() to continue the execution of subsequent filters and actions.
}
$filterChain (filter chain) is an instance of CFilterChain that represents a list of filters associated with the requested action. Within the filter method, we can call $filterChain->run() to continue executing subsequent filters and actions.
Like an action, a filter can also be an object, which is an instance of CFilter or its subclasses. The following code defines a new filter class:
class PerformanceFilter extends CFilter
{
protectedfunction preFilter($filterChain)
{
// The logic applied before the action is executed
return true; // If the action should not be executed, Returns false here
}

protected function postFilter($filterChain)
{
//Logic applied after the action is executed
}
}

To apply filters to the action, we need to override the CController::filters() method. This method should return an array of filter configurations. For example:
class PostController extends CController
{
...
public function filters()
{
return array(
'postOnly + edit, create',//Apply postOnly filters to edit and create actions (this It is a method-based filter)
array( //An array is used to configure the filter
'application.filters.PerformanceFilter - edit, create',//Apply the application.filters.PerformanceFilter filter to all actions except edit and create (this is an object-based filter)
'unit'=>' second', //Initialize the unit attribute value in the filter object to second
),
);
}
}
The above code specifies two filters: postOnly and PerformanceFilter. The postOnly filter is method-based (the corresponding filter method has been defined in CController); while the performanceFilter filter is object-based. The path alias application.filters.PerformanceFilter specifies that the filter class file is protected/filters/PerformanceFilter. We configure the PerformanceFilter using an array so that it can be used to initialize the filter object's property values. Here the unit attribute value of PerformanceFilter will be initialized to second.

Using the plus and minus signs, we can specify which actions should or should not have the filter applied. In the above code, postOnly should only be applied to edit and create actions, and PerformanceFilter should be applied to actions other than edit and create. If no plus or minus sign is used in the filter configuration, this filter will be applied to all actions.

5. Model (Model)
A model is an instance of CModel or its subclass. Models are used to hold data and the business logic associated with it.
Models are separate data objects. It can be a row in a data table, or a user-entered form.
Each field of the data object corresponds to an attribute in the model. Each attribute has a label and can be verified by a series of rules.
Yii implements two types of models: form model and Active Record. Both inherit from the same base class CModel.
Form models are instances of CFormModel. The form model is used to hold data obtained from the user's input. This data is often acquired, used, and then discarded. For example, in a login page, we can use the form model to represent the username and password information provided by the end user.
Active Record (AR) is a design pattern for abstracting database access in an object-oriented style. Each AR object is an instance of CActiveRecord or one of its subclasses. Represents a row in the data table. The fields in the row correspond to properties in the AR object.

6. View
A view is a PHP script that contains the main user interaction elements.
The view has a name, and when rendering (render), the name will be used to identify the view script file. The view's name is the same as its view script name. For example: the name of the view edit comes from a script file named edit.php. To render, call CController::render() by passing the name of the view. This method will search for the corresponding view file in the "protected/views/controller ID" directory.
Inside the view script, we can access the controller instance through $this. We can get any property of the controller in the view using "$this->property name".
We can also pass data to the view using the following push method:
$this->render('edit', array(
'var1'=>$value1,
'var2'=>$value2,
));
In the above method, the render() method will extract the second parameter of the array into a variable. The result of this is that in the view script, we can directly access the variables $var1 and $var2.
1. Layout
Layout is a special view file used to modify views. It usually contains a common part of the user interface view. For example: a layout can contain header and footer parts, and then embed content in between.

...header here...

...footer here...

where $content is Stores the rendering results of the content view.
When using render(), layout is applied implicitly. The view script protected/views/layouts/main.php is the default layout file. This can be customized by changing CWebApplication::layout. To render a view without a layout, call renderPartial().
2. Small objects
Small objects are instances of CWidget or its subclasses. It is a component mainly used to represent data. Widgets are often embedded in a view to produce complex and independent user interfaces. For example, a calendar widget can be used to render a complex calendar interface. Gizmos make user interfaces more reusable.
We can use a widget as follows:
beginWidget('path alias of widget class'[,'array containing attribute initialization values']);?>
...the content body that may be obtained by the widget...
endWidget();?>
or
widget('Widget class The path alias '[,'array containing attribute initialization values']);?>
The latter is used for components that do not require any body content.
Widgets can be configured to customize their performance. This is done by calling CBaseController::beginWidget or CBaseController::widget to set its initialization property value.
We do this by passing an array carrying the initialization values ​​​​of these properties. The keys of the array are the names of the properties, and the values ​​of the array are the values ​​corresponding to the widget properties. As shown below:
$this->widget('CMaskedTextField',array(
'mask'=>'99/99/9999'
));
?>
Inherit CWidget and override it Its init() and run() methods can define a new widget:
class MyWidget extends CWidget
{
publicfunction init()
{
// This method will be called by CController::beginWidget()
}
publicfunction run()
{
// This method will be called by CController::endWidget()
}
}
Widgets can have their own views like a controller.
By default, the view files of small objects are located under the views subdirectory (protected/components/views) that contains the directory of small object class files. These views can be rendered by calling CWidget::render(), much like a controller. The only difference is that the widget's view does not have layout file support. In addition, $this in the widget view points to the widget instance rather than the controller instance.

3. System view
Rendering of system view is usually used to display Yii errors and log information.
The naming of system views follows some rules. For example, a name like "errorXXX" is used to render the view showing CHttpException with error number XXX. For example, if CHttpException throws a 404 error, then error404 will be displayed.
Under framework/views, Yii provides a series of default system views. They can be customized by creating view files with the same name under protected/views/system.

7. Components
Yii applications are built on components. A component is an instance of CComponent or one of its subclasses. Using a component mainly involves accessing its properties and when to trigger or handle it. The base class CComponent specifies how properties and events are defined.
1. Component properties
The properties of a component are like the public member variables of an object. It is readable and writable.
To define a component property, we only need to define a public member variable in the component class.
A more flexible way is to define its getter and setter methods, for example:
public functiongetTextWidth() // Get the textWidth property
{
return$this->_textWidth;
}
public functionssetTextWidth($value) // Set the TextWidth property
{
$this->_textWidth=$value;
}
The above code defines a writable property named textWidth (the name is case-insensitive). When a property is read, getTextWidth() is called, and its return value becomes the property value; similarly, when a property is written, setTextWidth() is called. If the setter method is not defined, the property will be read-only and an exception will be thrown if written to it. One benefit of defining a property using getter and setter methods is that when the property is read or written, additional logic can be performed (e.g., performing validations, triggering events).
Note: There is a subtle difference between properties defined via getters/setters and class member variables: property names are case-insensitive, while class member variables are case-sensitive.
2. Component events
Component events are special properties that use methods called event handlers as their values. Assigning a method to an event will cause the method to be automatically called when the event is raised. Therefore, the behavior of a component may be modified in a way that was unforeseen during component development.
Component events are defined with naming starting with on. Like properties defined through getter/setter methods, event names are case-insensitive. The following code defines an onClicked event:
public function onClicked($event)
{
$this->raiseEvent('onClicked', $event);
}
$event as an event parameter here is CEvent or its subclass instance.
We can assign a method to this event as follows:
$component->onClicked=$callback;
Here $callback points to a valid PHP callback. It can be a global function or a method in a class. If the latter is the case, it must be provided as an array: array($object,'methodName').
The structure of the event handler is as follows:
function method name ($event)
{
...
}
$event here is the parameter describing the event (it comes from the raiseEvent() call). The $event parameter is an instance of CEvent or one of its subclasses. At the very least, it contains information about who triggered the event.
The event handler can also be an anonymous function supported by PHP 5.3 or later. For example:
$component->onClicked=function($event) {
...
}
If we call onClicked() now, the onClicked event will be triggered (in onClicked()), and the attached event The handle will be called automatically.
An event can be bound to multiple handles. When an event fires, these handlers will be executed in the order in which they were bound to the event. If the handler decides to prevent subsequent handlers from being executed, it sets $event->handled to true.
3. Component behavior
Components have added support for mixins and can bind one or more behaviors. A behavior is an object whose methods can be inherited by the components it is bound to by collecting functions, rather than specialized inheritance (i.e. ordinary class inheritance). A component can implement the binding of multiple behaviors through 'multiple inheritance'.
Behavior classes must implement the IBehavior interface. Most behaviors can be inherited from CBeavior . If a behavior needs to be bound to a model, it can also inherit from CModelBehavior or CActiveRecordBehavior which implement binding features specifically for the model.
To use a behavior, it must first be bound to a component by calling this behavior's attach() method. Then we can call this behavior method through the component:
// $name uniquely identifies the behavior in the component
$component->attachBehavior($name,$behavior);
// test() is in the behavior Methods.
$component->test();
Bound behaviors can be accessed like normal properties in a component. For example, if a behavior named tree is bound to a component, we can get a reference to this behavior through the following code.
$behavior=$component->tree;
// is equal to the following code:
// $behavior=$component->asa('tree');
The behavior can be temporarily prohibited, at this time its method will fail in the component. For example:
$component->disableBehavior($name);
// The following code will throw an exception
$component->test();
$component->enableBehavior($name);
// You can use it now
$component->test();
It is possible to bind two behaviors with the same name to the same component. In this case, the action that binds first takes precedence.
Behaviors are even more powerful when used with events. When a behavior is bound to a component, some methods in the behavior can be bound to some events of the component. In this way, behavior can be observed organically or change the component's regular execution flow.
Properties of a behavior can also be accessed through the component it is bound to. These properties include public member variables and properties set via getters and/or setters. For example, if a behavior has a property xyz and this behavior is bound to component $a, then we can access the property of this behavior using the expression $a->xyz.

8. Module
A module is an independent software unit that contains models, views, controllers and other supporting components. In many ways, a module looks like an application. The main difference is that a module cannot be deployed individually, it must exist within an application. Users can access controllers in a module just like they would access controllers in a normal application.
Modules are useful in some scenarios. For large applications, we may need to divide it into several modules, and each module can be maintained and deployed independently. Some common functions, such as user management and comment management, can be developed in the form of modules so that they can be easily reused in future projects.
1. Create a module
Modules are organized in a directory, and the directory name is the unique ID of the module. The structure of the module directory is very similar to the application base directory. The typical directory structure of a fourm module is listed below:
forum/ module folder
ForumModule.php module class file
components/ contains reusable user components
views/ contains view files for small objects
controllers/ contains Controller class file
DefaultController.php Default controller class file
extensions/ Contains third-party extensions
models/ Contains model class files
views/ Contains controller views and layout files
layouts/ Contains layout files
default/ Contains DefaultController View file
index.php Home page view file

module must have a module class inherited from CWebModule. The name of the class is determined by the expression ucfirst($id).'Module', where $id represents the ID of the module (or the directory name of the module). Module classes are the central place for storing information that can be shared between module code. For example, we can use CWebModule::params to store module parameters and use CWebModule::components to share module-level application components.
2. Use modules
To use modules, first place the module directory in the modules folder of the application base directory. Then declare the module ID in your app's modules attribute. For example, in order to use the forum module above, we can use the following application configuration:
return array(
...
'modules'=>array('forum',...),
.... ..
);
Modules can also be configured with initial property values. The approach is very similar to configuring application components. For example, the forum module can have a property called postPerPage in its module class, which can be configured in the application configuration as follows:
return array(
...
'modules'=>array(
'forum '=>array(
'postPerPage'=>20,
),
),
......
);
Instances of modules are accessible through the module property of the currently active controller. Within a module instance, we can access information shared at the module level. For example, to access the postPerPage information above, we can use the following expression:
$postPerPage=Yii::app()->controller->module->postPerPage;
// For example, $this refers to the control controller instance, you can use the following statement
//$postPerPage=$this->module->postPerPage;
The controller action in the module can be routed through "Module ID/Controller ID/Action ID" or "Module ID" /Subdirectory name where controller class files are stored/Controller ID/Action ID" access. For example, assuming the forum module above has a controller named PostController, we can access the create action in this controller through the route forum/post/create. The URL corresponding to this route is http://www.example.com/index.php?r=forum/post/create.
3. Nested modules
Modules can be nested infinitely. This means that one module can contain another module, and this other module can contain other modules. We call the former a parent module and the latter a submodule. Submodules must be defined in the modules attribute of their parent module, just like we defined the module in the application configuration earlier.
To access controller actions in submodules, we should use route parent module ID/submodule ID/controller ID/action ID.

9. Path aliases
Path aliases are widely used in Yii. A path alias is associated with the path of a directory or file. It is specified in dot syntax, similar to the widely used namespace format:
RootAlias.path.to.target
where RootAlias ​​is an alias of an existing directory. By calling YiiBase::setPathOfAlias(), we can Define a new path alias. For convenience, Yii predefines the following root aliases:
system: represents the Yii framework directory;
zii: represents the Zii library directory;
application: represents the base directory of the application;
webroot: represents the directory where the entry script file is located.
ext: Represents the directory containing all third-party extensions.
In addition, if the application uses modules, (Yii) also defines a root alias for each module ID, pointing to the root directory of the corresponding module.
By using YiiBase::getPathOfAlias(), aliases can be translated to their corresponding paths.
Using aliases can easily import class definitions. For example, if we want to include the definition of the CController class, we can call the following code
Yii::import('system.web.CController');
The import method is different from include and require, and it is more efficient. An imported class definition is not actually included until it is referenced for the first time. Importing the same namespace multiple times will also be much faster than include_once and require_once.
We can also use the following syntax to import the entire directory, so that class files in this directory will be automatically included when needed.
Yii::import('system.web.*');
In addition to import, aliases also point to classes in many other places. For example, a path alias can be passed to Yii::createComponent() to create an instance of the corresponding class. Even if the class file has never been included before.
Don’t confuse path aliases with namespaces. A namespace refers to a logical combination of class names so that they can be distinguished from each other, even if they have the same name. The path alias is used to point to a class file or directory. Path aliases do not conflict with namespaces.

The above is the content of the reprint, please indicate the source: Yii Quick Start (2). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



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
php如何使用Yii3框架?php如何使用Yii3框架?May 31, 2023 pm 10:42 PM

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

如何使用PHP框架Yii开发一个高可用的云备份系统如何使用PHP框架Yii开发一个高可用的云备份系统Jun 27, 2023 am 09:04 AM

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

快速入门:使用Go语言函数实现简单的数据聚合功能快速入门:使用Go语言函数实现简单的数据聚合功能Jul 29, 2023 pm 02:06 PM

快速入门:使用Go语言函数实现简单的数据聚合功能在软件开发中,我们经常会遇到需要对一组数据进行聚合的情况。聚合操作可以统计、汇总、计算等,对数据进行分析和展示。而在Go语言中,我们可以使用函数来实现简单的数据聚合功能。首先,我们需要定义一个数据类型来表示我们要进行聚合的数据。假设我们有一个学生的成绩表,每个学生有姓名和成绩两个字段,那么我们可以创建如下的结构

Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Jun 19, 2023 am 08:09 AM

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

Symfony vs Yii2:哪个框架更适合开发大型Web应用?Symfony vs Yii2:哪个框架更适合开发大型Web应用?Jun 19, 2023 am 10:57 AM

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

Yii框架中的数据查询:高效地访问数据Yii框架中的数据查询:高效地访问数据Jun 21, 2023 am 11:22 AM

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

yii如何将对象转化为数组或直接输出为json格式yii如何将对象转化为数组或直接输出为json格式Jan 08, 2021 am 10:13 AM

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。

Yii2编程指南:运行Cron服务的方法Yii2编程指南:运行Cron服务的方法Sep 01, 2023 pm 11:21 PM

如果您问“Yii是什么?”查看我之前的教程:Yii框架简介,其中回顾了Yii的优点,并概述了2014年10月发布的Yii2.0的新增功能。嗯>在这个使用Yii2编程系列中,我将指导读者使用Yii2PHP框架。在今天的教程中,我将与您分享如何利用Yii的控制台功能来运行cron作业。过去,我在cron作业中使用了wget—可通过Web访问的URL来运行我的后台任务。这引发了安全问题并存在一些性能问题。虽然我在我们的启动系列安全性专题中讨论了一些减轻风险的方法,但我曾希望过渡到控制台驱动的命令

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development 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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment