Home  >  Article  >  php教程  >  Quick Start with Yii (2)

Quick Start with Yii (2)

黄舟
黄舟Original
2016-12-20 11:08:40949browse

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
Previous article:Quick Start with Yii (1)Next article:Quick Start with Yii (1)