Introduction to yiiframework 6

Source: Internet
Author: User
Tags zend framework

Http://vmee.org/yiiframework%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%E5%8D%81%E5%9B%9B%E4%B9%8B%E6%89%A9%E5%B1%95

14. Extension yii is a common behavior during development. for example, when you write a new controller, you extend yii by inheriting the ccontroller class. When you write a new component, you are inheriting cwidget or an existing component class. if the extension code is designed for reuse by third-party developers, we call it extension ). An extension is usually used for a single purpose. in yii, it can be classified as follows: * application component * controller * Action * filter * Console Command * Checker: The checker is a component inherited from the cvalidator class. * Helper: the Helper is a class with only static methods. It is similar to using a class name as a global function of the namespace. * Module: a module contains several class files and corresponding special files. A module is generally more advanced and provides more advanced functions than a single component. for example, we can have a complete set of user management functions. Extension can also be a component that does not belong to any of the above categories. In fact, yii is designed with caution so that almost every segment of its code can be extended and customized to suit specific needs. 1. Using extensions to use extensions usually involves the following three steps: 1. Download extensions from the yii extension library. 2. decompress the package to the extensions/XYZ subdirectory of the application's base directory. Here XYZ is the extension name. 3. Import, configure, and use extensions. Each extension has a unique name identifier for all extensions. Name an extension XYZ. You can also use the path alias to locate the base directory that contains all XYZ files. Different extensions have different import, configuration, and usage requirements. The following are the scenarios where we usually use extensions and classify them according to their descriptions in the overview. 1. The application parts use the application parts. First, we need to add a new entry to the components attribute of the application configuration, as shown below:
Return array (// 'preload' => array ('xyz ',...), 'components' => array ('xyz' => array ('class' => 'application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other part configuration ),);

Then, we can access parts anywhere by using yii: APP ()-> XYZ. the widget will be created with inertia (that is, only when it is accessed for the first time .), unless we configure it to the preload attribute.

2. Component components are mainly used in the view. If the component class xyzclass belongs to the XYZ extension, we can use it in the view as follows:
// Widget ('application. extensions. XYZ. xyzclass', array ('property1' => 'value1', 'property2' => 'value2');?> // The component can contain the subject content beginwidget ('application. extensions. XYZ. xyzclass', array ('property1' => 'value1', 'property2' => 'value2');?> ... Main body content of the component... endwidget ();?>
3. The action is used by the Controller to respond to the specified user request. Assuming that the action class xyzclass belongs to the XYZ extension, we can rewrite the ccontroller: Actions method in our controller class to use it:
Class testcontroller extends ccontroller {public function actions () {return array ('xyz' => array ('class' => 'application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other actions );}}
Then, we can access it through the test/XYZ route. 4. The filter is also used by the Controller. Filters are mainly used for preprocessing when they are suspended by actions and submitting and processing user requests. Assuming that the xyzclass of the filter class belongs to the XYZ extension, we can rewrite the ccontroller: filters method in our controller class to use it:
Class testcontroller extends ccontroller {public function filters () {return array (Array ('application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other filters );}}
In the above code, we can use the plus sign or minus operator to limit that the filter takes effect only in the first element of the array. For more information, see the ccontroller documentation. 5. The Controller provides a set of actions that can be requested by users. We need to set the cwebapplication: controllermap attribute in the application configuration to use the extension in the controller:
Return array ('controllermap' => array ('xyz' => array ('class' => 'application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other controllers ),);
Then, the action in the control can be accessed by routing XYZ/. 6. the validator is mainly used in model classes (inherited from cformmodel or cactiverecord. suppose the checker class xyzclass belongs to the XYZ extension, we can use it in our model class through cmodel: rules to override cmodel: rules:
Class mymodel extends cactiverecord // or cformmodel {public function rules () {return array (Array ('attr1, attr2', 'application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other validation rules );}}
7. The Console Command extension usually uses an additional command to enhance the yiic function. If the command console xyzclass belongs to the XYZ extension, we can use it by setting the configuration of the console application:
Return array ('commandmap' => array ('xyz' => array ('class' => 'application. extensions. XYZ. xyzclass', 'property1' => 'value1', 'property2' => 'value2',), // other commands ),);
Then we can use the yiic tool with the extra command XYZ. Note: The console application usually uses a configuration file different from the Web application. if you use the yiic webapp command to create an application, the configuration file of the console application protected/yiic is protected/config/console. PHP, while the web application configuration file is protected/config/main. PHP. 8. The module is usually composed of multiple class files and is often integrated with the above extension types. Therefore, you should use the module according to the following commands. 9. To use a universal part, you must first include its class file by using yii: Import ('application. Extensions. XYZ. xyzclass. Then, we can create a class instance, configure its attributes, or call its method. We can also create a new subclass to expand it. 2. Create an extension because it is used by third-party developers, some extra efforts are required to create it. Below are some general guiding principles: * expansion should be self-contained. That is to say, its external dependencies should be the least. If you need to install additional software packages, classes, or resource files for your extension, this will be a headache. * Files belonging to the same extension should be organized in the same directory, and the directory name should be extended. * Classes in the extension should use certain word/letter prefixes to avoid conflicts with other extension names. * The extension should provide detailed installation and API documentation. This reduces the time and effort spent by other developers when using extensions. * The extension should be licensed as appropriate. If you want your extensions to be used in open-source and closed-source projects, you can consider using licenses, such as BSD and MIT, but not GPL, because it requires the derived code to be open-source. Next, we will describe how to create a new extension based on the categories described in overview. These descriptions also apply when you create a component that is mainly used for your project. 1. Application Component an application component should implement the iapplicationcomponent interface or inherit the capplicationcomponent interface. The main implementation method is iapplicationcomponent: init. The component performs some initialization work here. This method is called after the component creation and attribute values (specified in application configuration) are assigned values. By default, an application part is created and initialized only when it is requested during its first access. If an application part needs to be created after the application instance is created, it requires the user to list its number in the attributes of capplication: preload. 2. widgets must inherit from cwidgets or their subclasses. A widget shoshould extend from cwidget or its child classes. The simplest way to create a new widget is to inherit a ready-made widget and reload its methods or change its default attribute values. For example, if you want to use a better CSS style for ctabview, you can configure its ctabview: cssfile attribute when using a small tool. You can also inherit the ctabview as follows, so that you do not need to configure attributes when using gadgets.
class MyTabView extends CTabView{public function init(){if($this->cssFile===null){$file=dirname(__FILE__).DIRECTORY_SEPARATOR.'tabview.css';$this->cssFile=Yii::app()->getAssetManager()->publish($file);}parent::init();}}
In the above section, we reload the cwidget: init method and specify the ctabview: cssfile URL to our new default CSS style if this attribute is not set. We put the new CSS style files and mytabview files in the same directory so that they can be encapsulated into extensions. Since CSS style files are not accessed through Web, we need to publish them as an asset resource. To create a new tool from scratch, we mainly need to implement two methods: cwidget: init and cwidget: Run. The first method is called when you use $ this-> beginwidget in the view to insert a small tool. The second method is called when $ this-> endwidget is called. If we want to capture and process the displayed content between the two method calls, we can start to output buffering in cwidget: init and reclaim the buffer output in cwidget: Run for further processing. If we want to capture and process the content displayed between these two method invocations, we can start output buffering in cwidget: init andretrieve the buffered output in cwidget: Run for further processing. small tools used in Web pages often include CSS, Java Script, or other resource files. We call these file assets because they are associated with the small tool class and are usually inaccessible to Web users. To make these files accessible through the Web, we need to use cwebapplication: assetmanager to publish them, as shown in the code snippet above. In addition, if we want to include CSS or Java script files on the current webpage, we need to use cclientscript for registration:
class MyWidget extends CWidget{protected function registerClientScript(){// ...publish CSS or java script file here...$cs=Yii::app()->clientScript;$cs->registerCssFile($cssFile);$cs->registerScriptFile($jsFile);}}
Gadgets may also have their own view files. In this case, create a directory named views under the directory containing the small tool files and put all the view files in it. Use $ this-> render ('viewname') in the tool class to render the rendering of the gadgets view, similar to what we do in the controller. 3. Action action should inherit caction or its subclass. The main method to implement action is iaction: Run. 4. filters should inherit from cfilter or its subclass. The main methods to implement the filter are cfilter: prefilter and cfilter: postfilter. The former is executed before the action, and the latter is later.
class MyFilter extends CFilter{protected function preFilter($filterChain){// logic being applied before the action is executedreturn true; // false if the action should not be executed} protected function postFilter($filterChain){// logic being applied after the action is executed}}
The $ filterchain parameter is of the cfilterchain type and contains information about the action currently filtered. 5. The controller must inherit cextcontroller as an extension, rather than ccontroller. The main reason is that ccontroller determines that the controller View File is located under application. Views. controllerid, and cextcontroller determines that the View File is under the views Directory, which is also a sub directory containing the Controller class directory. Therefore, it is easy to re-allocate the Controller because its view file and control class are together. 6. validator (verification) validator must inherit cvalidator and implement the cvalidator: validateattribute method.
class MyValidator extends CValidator{protected function validateAttribute($model,$attribute){$value=$model->$attribute;if($value has error)$model->addError($attribute,$errorMessage);}}

7. The Console Command (Console Command) console command should inherit the cconsolecommand and implement the cconsolecommand: Run method. Alternatively, we can overload cconsolecommand: gethelp to provide better help commands.

class MyCommand extends CConsoleCommand{public function run($args){// $args gives an array of the command-line arguments for this command} public function getHelp(){return 'Usage: how to use this command';}}
8. For details about how to create a module, see the module section. Generally, a module should be developed based on the guidelines, which should be independent. The resource files used by the module (such as CSS, Java Script, and images) should be distributed together with the module. Other modules should publish them so that they can be accessed on the Web. 9. Generic component (General Component) develops a general component extension, which is similar to writing a class. Also, this component should be self-contained so that it can be easily used by other developers.

Http://vmee.org/yiiframework%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%E5%8D%81%E4%BA%94%E4%B9%8B%E4%BD%BF%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93

15. The use of the third-party library yii is well-designed, so that the third-party library can be easily integrated to further expand the yii function. When a third-party library is used in a project, programmers often encounter class naming and file inclusion problems. Because all yii classes start with a C letter, this reduces possible class naming issues, and because yii depends on the splautoload execution class file, if they use the same automatic loading function or PHP contains path containing class files, it can be well combined. The following is an example to illustrate how a yii application uses zend_search_lucene components from Zend framework. First, if protected is the application base Directory, we extract the zendframework publishing file to the protected/vendors directory. Confirm that the protected/vendors/Zend/search/Lucene. php file exists. Second, add the following lines at the beginning of a controller file: yii: Import ('application. vendors. * '); require_once ('zend/search/Lucene. PHP '); the above Code contains the class file Lucene. PHP. Because we use relative paths, we need to change the PHP inclusion path so that the file can be located correctly. This is done by calling yii: import before require_once. Once the above setup is ready, we can use the Lucene class in the Controller action, for example: $ Lucene = new zend_search_lucene ($ pathofindex ); $ hits = $ Lucene-> Find (strtolower ($ keyword ));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.