Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get started with Yii

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to get started with Yii. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The details are as follows:

Ⅰ, basic concept

I. entry documents

Contents of the entry file: the general format is as follows:

.footer here.

The $content stores the rendering results of the content view.

When render () is used, the layout is implicitly applied. The view script protected/views/layouts/main.php is the default layout file. This can be customized by changing the CWebApplication::layout. To render a view without layout, call renderPartial ().

2. Small objects

A small object is an instance of CWidget or its subclass. It is a component that is mainly used to represent data. Small objects are usually 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. The user interface of small objects is more reusable.

We can use a small object by following the view script:

... A content body that may be obtained by a small object.

Or

The latter is used for components that do not require any body content.

A small object can be configured to customize its performance. This is done by calling CBaseController::beginWidget or CBaseController::widget to set the value of its initialization property.

We do this by passing an array that carries the initialization values of these attributes. The key of the array is the name of the property, and the value of the array is the value corresponding to the property of the small object. As follows:

Inheriting CWidget and overriding its init () and run () methods, you can define a new small object:

Class MyWidget extends CWidget {public function init () {/ / this method will be called by CController::beginWidget ()} public function run () {/ / this method will be called by CController::endWidget ()}}

A small object can have its own view like a controller.

By default, the view files for small objects are located under the views subdirectory (protected/components/views) that contains the small object class files directory. These views can be rendered by calling CWidget::render (), which is very similar to the controller. The only difference is that views of small objects are not supported by layout files. In addition, the $this in the gadget view points to the gadget instance rather than the controller instance.

3. System View

Rendering of the system view is often used to show Yii errors and log information.

The naming of system views follows some rules. For example, a name like "errorXXX" is used to render a view of the CHttpException that shows the 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 customize by creating a view file with the same name under protected/views/system.

VII. Components

Yii applications are built on top of components. A component is an instance of CComponent or its subclasses. Using a component mainly involves accessing its properties and the time it takes to trigger or process it. The base class CComponent specifies how properties and events are defined.

1. Component properties

The properties of a component are like 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, such as:

Public function getTextWidth () / / get textWidth attribute {return $this- > _ textWidth;} public function setTextWidth ($value) / / set TextWidth attribute {$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, setTextWidth () is called when the property is written. If the setter method is not defined, the property will be read-only and an exception will be thrown if it is written to. Using the getter and setter methods to define a property has the benefit of performing additional logic (for example, performing validation, triggering events) when the property is read or written.

Note: there is a slight difference between properties defined through getter/setter 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 called automatically where the event is called. As a result, the behavior of a component may be modified in an unpredictable way during component development.

Component events are defined in a naming manner that begins with on. The name of the event is case-insensitive in the same way that properties are defined by the getter/setter method. The following code defines an onClicked event:

Public function onClicked ($event) {$this- > raiseEvent ('onClicked', $event);}

$event, which is the event parameter here, is an instance of CEvent or its subclass.

We can assign a method to this event, as follows:

The copy code is as follows:

$component- > onClicked=$callback

The $callback here points to a valid PHP callback. It can be a global function or a method in a class. If it is the latter, it must be provided as an array: array ($object,'methodName').

The structure of the event handle is as follows:

Function method name ($event) {.}

The $event here is the parameter that describes the event (it comes from the raiseEvent () call). The $event parameter is an instance of CEvent or its subclass. At the very least, it contains information about who triggered the event.

The event handle can also be an anonymous function supported after PHP 5. 3. For example:

$component- > onClicked=function ($event) {.}

If we call onClicked () now, the onClicked event will be triggered (in onClicked ()) and the attached event handle will be invoked automatically.

Multiple handles can be bound to an event. When an event is triggered, these handles are executed in the order in which they were bound to the event. If the handle decides to organize the subsequent handle to be executed, it sets $event- > handled to true.

3. Component behavior

Component has added support for mixin and can bind one or more behaviors. A behavior is an object whose method can be bound to the widget by collecting functionality to implement inheritance (inherited) rather than exclusive inheritance (that is, normal class inheritance). A widget can bind multiple behaviors in the form of multiple inheritance.

The behavior class must implement the IBehavior interface. Most behaviors can be inherited from CBehavior. If a behavior needs to be bound to a model, it can also inherit from CModelBehavior or CActiveRecordBehavior that implements binding features specifically for the model.

To use a behavior, it must first bind to a component by calling the attach () method of the behavior. We can then call this behavior method through the component:

/ / $name implements unique identification of the behavior in the component $component- > attachBehavior ($name,$behavior); / / test () is the method in the behavior. $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 that behavior with the following code.

$behavior=$component- > tree;// equals the following code: / / $behavior=$component- > asa ('tree')

A behavior can be temporarily prohibited, at which point its methods are invalidated in the component. For example:

$component- > disableBehavior ($name); / / the following code will throw an exception $component- > test (); $component- > enableBehavior ($name); / / you can now use $component- > test ()

It is possible for two behaviors with the same name to be bound to the same component. In this case, the behavior that binds first has priority.

When used with events, the behavior is more powerful. 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, the behavior organically observes or changes the routine execution flow of the component.

The properties of a behavior can also be accessed through the component that is bound to. These properties contain public member variables and properties that are set through getters and / or setters. For example, if a behavior has a property of xyz, the behavior is bound to the component $a, and then we can access the property of this behavior using the expression $a-> xyz.

VIII. Module

A module is a separate software unit that contains models, views, controllers, and other supported components. In many ways, the module looks like an application. The main difference is that the module cannot be deployed separately, it must exist in an application. Users can access the controller in the module as they access the controller of a common application.

Modules are useful in some scenarios. For large applications, we may need to divide it into several modules, each of which can be maintained and deployed separately. Some common functions, such as user management and comment management, can be developed as modules so that they can be easily reused in future projects.

1. Create a module

The module is organized in a directory, and the directory name is the unique ID of the module. The structure of the module directory is similar to that of 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 files

DefaultController.php default controller class file

Extensions/ includes third-party extensions

Models/ contains model class files

Views/ contains controller views and layout files

Layouts/ contains layout files

Default/ contains the view file of DefaultController

Index.php Home View File

The module must have a module class that inherits from CWebModule. The name of the class is determined by the expression ucfirst ($id). 'Module', where $id represents the module's ID (or module's directory name). The module class is the central location where information can be shared between enclosure code. For example, we can use CWebModule::params enclosure parameters and CWebModule::components to share module-level application components.

2. Use the module

To use the module, first place the module directory in the modules folder of the application base directory. Then declare the module ID in the modules property of the application. For example, 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 practice is similar to configuring application components. For example, a 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,),.)

An instance of the module can be accessed through the module property of the currently active controller. In the module example, we can access the 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;// if $this refers to a controller instance, you can use the following statement / / $postPerPage=$this- > module- > postPerPage

The controller actions in the module can be accessed by routing "module ID/ controller ID/ action ID" or "module ID/ stores the subdirectory name of the controller class file / controller ID/ action ID". For example, assuming that the above forum module has a controller named PostController, we can access the create actions in this controller by routing 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 at unlimited levels. That is to say, one module can contain another module, which in turn can contain other modules. We call the former the parent module and the latter the child module. The child module must be defined in the modules property of its parent module, just as we defined the module in the application configuration earlier.

To access the controller actions in the submodule, we should use the routing parent module ID/ submodule ID/ controller ID/ action ID.

9. Path alias

Path aliases are widely used in Yii. The path alias is associated with the path of a directory or file. It is specified in period syntax, similar to the widely used namespace (namespace) format:

RootAlias.path.to.target

Where RootAlias is an alias for an existing directory, and 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: indicates the directory where the entry script file is located.

Ext: represents a directory that contains all third-party extensions.

In addition, if the application uses modules, (Yii) also defines a root alias for each module ID, pointing to the following directory of the corresponding module.

By using YiiBase::getPathOfAlias (), aliases can be translated to their corresponding paths.

Using aliases makes it easy to import class definitions. For example, if we want to include the definition of the CController class, we can call the following code

The copy code is as follows:

Yii::import ('system.web.CController')

Unlike include and require, the import method is more efficient. The class definition of the import is not really included until it is referenced for the first time. Importing the same namespace multiple times can also be much faster than include_once and require_once.

We can also import the entire directory using the following syntax so that the class files in this directory are automatically included when needed.

The copy code is as follows:

Yii::import ('system.web.*')

Besides import, aliases 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, which are 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.

X. development norms

Let's explain the recommended development specifications in Yii programming. For simplicity, let's assume that WebRoot is the directory where the Yii application is installed.

1 、 URL

By default, Yii recognizes URL in the following format:

Http://hostname/index.php?r=ControllerID/ActionID

The r variable means route, which can be parsed by Yii as controllers and actions. If ActionID is omitted, the controller will use the default action (defined in CController::defaultAction); if ControllerID is also omitted (or the r variable does not exist), the application will use the default controller (defined in CWebApplication::defaultController).

With the help of CUrlManager, you can create more recognizable and SEO-friendly URL, such as http://hostname/ControllerID/ActionID.html.

2. Code

Yii recommends naming variables, functions, and classes in the hump style, where the first letters of each word are capitalized and concatenated with no spaces in the middle. Variable and function names should be lowercase in all their first words to distinguish them from class names. For private class member variables, we recommend the following underscore as its name prefix (for example: $_ actionList).

A special rule for controller class names is that they must end with the word Controller. Then the controller ID is the first letter of the class name in lowercase and the word Controller is removed. For example, the ID of the PageController class is page. This rule makes the application more secure. It also makes the controller-related URL simpler (for example, / index.php?r=page/index instead of / index.php?r=PageController/index).

3. Configuration

The configuration is a key-value pair array. Each key represents the name of the property in the configured object, and each value is the initial value of the corresponding property.

Any writable property in the class can be configured. If it is not configured, the properties use their default values. When configuring a property, it is best to read the documentation to ensure that the initial value is correct.

4. Files

The specification for naming and using files depends on their type.

Class files should be named after the public classes they contain. For example, the CController class is located in the CController.php file. Public classes are classes that can be used by any other class. Each class file should contain at most one public class. A private class (a class that can only be used by a public class) can be placed in the same file as the public class that uses it.

The view file should be named after the view. For example, the index view is located in the index.php file. The view file is an PHP script file that contains HTML and PHP code for rendering content.

The configuration file can be named at will. The configuration file is a PHP script whose main purpose is to return an associative array that reflects the configuration.

5. Catalogue

Yii assumes a series of default directories for different situations. Each directory can be customized if necessary.

WebRoot/protected: this is the application base directory, where all the security-sensitive PHP scripts and data files are placed. Yii has a default application alias that points to this directory. This directory and the files in this directory should be protected from Web users. It can be customized through CWebApplication::basePath.

WebRoot/protected/runtime: this directory holds private temporary files generated by the application at run time. This directory must be writable to the Web server process. It can be customized through CApplication::runtimePath.

WebRoot/protected/extensions: this directory places all third-party extensions. It can be customized through CApplication::extensionPath.

WebRoot/protected/modules: this directory places all application modules, each using a subdirectory.

WebRoot/protected/controllers: this directory places all controller class files. It can be customized through CWebApplication::controllerPath.

WebRoot/protected/views: this directory places all attempt files, including controller view, layout view, and system view. It can be customized through CWebApplication::viewPath.

WebRoot/protected/views/ControllerID: this directory places the view files used in a single controller class. The ControllerID here refers to the ID of the controller. It can be customized through CController::viewPath.

WebRoot/protected/views/layouts: this directory places all layout view files. It can be customized through CWebApplication::layoutPath.

WebRoot/protected/views/system: this directory places all system view files. The system view file is a template for displaying exceptions and errors. It can be customized through CWebApplication::systemViewPath.

WebRoot/assets: this directory places public resource files. Resource files are private files that can be published and accessed by Web users. This directory must be writable to the Web server process. It can be customized through CAssetManager::basePath

WebRoot/themes: this directory places different themes used by the application. Each subdirectory is a topic, and the name of the topic is the name of the directory. It can be customized through CThemeManager::basePath.

6. Database

Most Web applications are database driven. We recommend that you use the following naming convention when naming tables and columns. Note that these specifications are not required for Yii.

㈠ database table and column names are named in lowercase.

Words in ㈡ names should be separated by underscores (for example, product_order).

㈢ you can use either the singular or the plural for table names. But don't use both. For simplicity, we recommend using singular names.

㈣ table names can use a common prefix, such as tbl_. This is especially useful when the table used by the application and the table used by another application coexist in the same database. The tables of these two applications can be easily separated by using different table prefixes.

Ⅱ, using forms

When working with forms in Yii, you usually need the following steps:

1. Create a model class that represents the fields of data you want to collect.

two。 Create a controller action in response to the form submission.

3. Create a form related to the controller action in the view script.

First, create a model

Before writing the HTML code required for the form, we should determine the type of data input from the end user and what rules the data should conform to. Model classes can be used to record this information. As defined in the model section, the model is the central location for saving and validating user input.

Depending on how the data entered by the user is used, we can create two types of models. If the user input is collected, used, and then discarded, we should create a form model; if the user input is collected and saved to the database, we should use an Active Record. Both types of models share the same base class CModel, which defines the common interface required by the form.

1. Define the model class

For example, create as a form model:

Class LoginForm extends CFormModel {public $username;public $password;public $rememberMe=false;}

Three properties are defined in LoginForm: $username, $password, and $rememberMe. They are used to save the user name and password entered by the user, as well as the option of whether the user wants to remember his login. Because $rememberMe has a default value of false, the corresponding option will be unchecked when initialized in the login form.

We call these member variables attributes rather than properties to distinguish them from ordinary attributes. An attribute is an attribute (propertiy) that is primarily used to store data from user input or database.

2. Declare validation rules

Once the user submits his input and the model is populated, we need to make sure that the user's input is valid before using it. This is achieved by validating the user's input and a series of rules. We specify these validation rules in the rules () method, which should return an array of rule configurations.

Class LoginForm extends CFormModel {public $username;public $password;public $rememberMe=false;private $_ identity;public function rules () {return array (array ('username, password',' required'), / / username and password are required array ('rememberMe',' boolean'), / / rememberMe should be a Boolean array ('password',' authenticate'), / / password should be verified (authenticated);} public function authenticate ($attribute,$params) {$this- > _ identity=new UserIdentity ($this- > username,$this- > password) If (! $this- > _ identity- > authenticate ()) $this- > addError ('password',' wrong user name or password.') ;}}

Each rule returned by rules () must be in the following format:

Array ('AttributeList',' Validator', 'on'= >' ScenarioList',. Additional options) Thank you for your reading! This is the end of the article on "how to get started with Yii". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report