Home > php教程 > PHP开发 > body text

Quick Start with Yii (1)

黄舟
Release: 2016-12-20 11:07:22
Original
1338 people have browsed it

Please indicate the source when reprinting: Yii Quick Start (1)

Ⅰ. Basic concepts
1. Entry file
Entry file content: The general format is as follows:

$yii=dirname(__FILE__).'/../../framework/yii.php';/ /Yii framework location
$config=dirname(__FILE__).'/protected/config/main.php';//The main configuration file location of the current application

// When deploying the formal environment, remove the following line
// defined('YII_DEBUG') or define('YII_DEBUG',true);//Whether to run in debug mode

require_once($yii);//Contains Yii framework
Yii::createWebApplication($config)->run ();//Create an application instance based on the main configuration file and run it. You can access this instance through Yii::app() from anywhere in the current application.


2. Main configuration file
Save location: your application/protected/config/main.php
File content: The general format is as follows:
return array(
'basePath'=>dirname(__FILE__ ).DIRECTORY_SEPARATOR.'..', //The absolute physical path of the current application root directory
'name'=>'Yii Blog Demo', //The name of the current application

//Preload the log (record) application Components, which means that the application components will be created regardless of whether they are accessed. The application's parameter configuration is set in the array with "components" as the keyword below.
'preload'=>array('log'), //log is the component ID

//Auto-loaded model and component class
'import'=>array(
'application.models.*', //Load the "application/models/" folder All model classes
        'application.components.*', //Load all application component classes in the "application/components/" folder
   ),

  'defaultController'=>'post', //Set the default control Device class

// Component configuration of the current application. For more configuration components, see "Core Application Components" below
'components'=>array(
'user'=>array( //user( User) component configuration, "user" is the component ID
              // Cookie-based authentication can be used
            'allowAutoLogin'=>true, // Allow automatic login
                                                                                                             
                                                                                                                                                                ,,,,,,,,,,,,,,,,,,,,,, , 'port'=> 11211, 'weight'=>60), //Cache server 1
                               array('host'=>'server2', 'port'=>11211, 'weight'=>40), //Cache server 2
  // DSN string to connect to the database
        'tablePrefix' => 'tbl_', //Data table prefix
          ),
          // If you want to use a MySQL database, please uncomment the following
             
    'errorHandler'=> Array (使用 // uses the ActionError method in the SiteController controller class to display the error
'erraraction' = & gt; 'site/error', // When encountering errors, run operations. The controller name and method name are all lowercase and separated by slashes "/"
      ),
    //URL routing manager
    'urlManager'=>array(
            'urlFormat'=>'path', //URL format. Two formats are supported: 'path' format (such as: /path/to/EntryScript.php/name1/value1/name2/value2...) and 'get' format (such as: /path/to/EntryScript.php? name1=value1&name2=value2...). When using the 'path' format, you need to set the following rules:
            'rules'=>array( //URL rules. Syntax:
                                                                                                                                                       >/'=>'post/view', //Point post/12/helloword to post/view?id=12&title=helloword
                                            'posts/'=>'post/index', //Point posts/hahahaha to post/index?tag=hahahaha
                    '/'=> '/',
          ),
       ),
      'log'=>array( //记录
         'class'=>'CLogRouter', //处理记录信息的类
         ' routes'=>array(
                                                                                using   using using ‐               ‐                                                                       ’ s ’ s ’ s ‐ ‐ ‐ ‐ to ),
                                   / If you want to display the error log message on the web page, just cancel the comment below
                                                                                                                                                                                                                                to be displayed on the page
   ['Parameter name'] can access the parameters of the application layer
'params'=>require(dirname(__FILE__).'/params.php'),
);

Core application components:
Yii predefined a series of Core application components provide functionality used in common web applications. For example, the request component is used to parse user requests and provide information such as URLs, cookies, etc. By configuring the properties of these core components, we can modify Yii's default behavior almost arbitrarily.

Below we list the core components predefined by CWebApplication.
assetManager: CAssetManager - manages the release of private asset files.
authManager: CAuthManager - Manages role-based access control (RBAC).
cache: CCache - Provides data caching functionality. Note that you must specify the actual class (eg CMemCache, CDbCache). Otherwise, NULL will be returned when you access this component.
clientScript: CClientScript - Manages client-side scripts (javascripts and CSS).
coreMessages: CPhpMessageSource - Provides translations of core messages used by the Yii framework.
db: CDbConnection - Provides database connection. Note that to use this component you must configure its connectionString property.
errorHandler: CErrorHandler - Handles uncaught PHP errors and exceptions.
format: CFormatter - formatted numerical display. This feature is available starting with version 1.1.0.
messages: CPhpMessageSource - Provides message translations used in Yii applications.
request: CHttpRequest - Provides information about the user's request.
securityManager: CSecurityManager - Provides security related services such as hashing, encryption.
session: CHttpSession - Provides session-related functions.
statePersister: CStatePersister - Provides global state persistence methods.
urlManager: CUrlManager - Provides URL parsing and creation related functions
user: CWebUser - Provides identification information of the current user.
themeManager: CThemeManager - Manage themes.

To access an application component, use Yii::app()->ID of the component

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 letters 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 404 CHttpException 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 a action class, the basic format is as follows:
Class UpdateAction Extends Caction
{
Public Function Run () {
// Place the Action logic here
}}}}}}}}}}}: Noting this action, we have to override the actions() method of the controller class in the following way:
class PostController extends CController
{
 public function actions()
 {
                                                                                  use using                               ‐                                                                         .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
                                                        ListAction.php
               ProfileAction.php
                                                                                ListAction.A filter is a piece of code that can be configured to execute before or after a controller action.
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 related to 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
{
 protected function preFilter($filterChain)
 {
                                            use   use using with using using using            through , Here, return false
}

Proteable Function Postfilter ($ Filterchain) {
// The logic of the application after the action execution is to be applied to the action application filter, we need to cover the ccontroller :: filers () method . This method should return an array of filter configurations. For example:
class PostController extends CController
{
 …
 public function filters()
 {
          return array(
                                                     This 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 anything except edit and create All the movements outside (this is an object -based filter)
'unit' = & gt; 'second', // Initialize the unit property value in the object of the filter object is second
),
}}}
The above code Two filters are specified: 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 with 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 be applied only to edit and create actions, and PerformanceFilter should be applied to actions other than edit and create. If the plus or minus sign is not 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.
Views have a name, which is used to identify the view script file when rendering. 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 use the following push method to pass data to the view:
$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 key of the array is the name of the property, and the value of the array is the value corresponding to the small object property. 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
{
 public function init()
 {
            // This method will be called by CController::beginWidget()
  }
public function run()
                                                                                                      // This method will be called by CController::endWidget()
      }
}
A widget can have its own view 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 function getTextWidth() // Get the textWidth property
{
return $this->_textWidth;
}
public function setTextWidth($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, 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 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
The component has 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.
A behavior's properties 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, 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 files
Components/contains reusable user components
Views containing small objects
Controllers/containing 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
                                                                                                                                                 can be View files
index.php home view file

Module must have a module class that inherits 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 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 named postPerPage in its module class, which can be configured in the application configuration as follows:
return array(
 ...
  'modules'=>array(
    'forum '=>array(
 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 container instance, you can use the following statement
// $postPerPage=$this->module->postPerPage;
The controller actions in the module can be accessed through the route "Module ID/Controller ID/Action ID" or "Module ID/Subdirectory name where the controller class file is stored/Controller ID/Action ID". 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.

10. Development specifications
Below we 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 URLs in the following format:
http://hostname/index.php?r=ControllerID/ActionID
r variable means route, which can be parsed by Yii as a controller and action. 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 identifiable and SEO-friendly URLs, such as http://hostname/ControllerID/ActionID.html.
2. Code
Yii recommends using camel case style when naming variables, functions and classes, that is, the first letter of each word is capitalized and connected together, without spaces in between. Variable and function names should have their first word all lowercase to distinguish them from class names. For private class member variables, we recommend prefixing their names with an underscore (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 controller-related URLs simpler (e.g. /index.php?r=page/index instead of /index.php?r=PageController/index).
3. Configuration
Configuration is an array of key-value pairs. Each key represents the property name 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 not configured, properties will use their default values. When configuring a property, it's a good idea to read the documentation to ensure the initial values ​​are correct.
4. Files
The convention 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. A public class is a class that can be used by any other class. Each class file should contain at most one public class. Private classes (classes that can only be used by one public class) can be placed in the same file as the public class that uses them.
View files should be named after the view. For example, the index view is located in the index.php file. A view file is a PHP script file that contains the HTML and PHP code used to render content.
The configuration file can be named arbitrarily. A configuration file is a PHP script whose main purpose is to return an associative array that embodies the configuration.
5. Directory
Yii assumes a series of default directories for different occasions. Each directory can be customized if needed.
WebRoot/protected: This is the application base directory, where all security-sensitive PHP scripts and data files are placed. Yii has a default application alias pointing to this directory. This directory and the files in it should be protected from access by web users. It can be customized via CWebApplication::basePath.
WebRoot/protected/runtime: This directory contains private temporary files generated when the application is running. This directory must be writable by the web server process. It can be customized via CApplication::runtimePath.
WebRoot/protected/extensions: This directory places all third-party extensions. It can be customized via CApplication::extensionPath.
WebRoot/protected/modules: This directory places all application modules, and each module uses a subdirectory.
WebRoot/protected/controllers: This directory places all controller class files. It can be customized via CWebApplication::controllerPath.
WebRoot/protected/views: This directory places all view files, including controller views, layout views and system views. It can be customized via CWebApplication::viewPath.
WebRoot/protected/views/ControllerID: This directory places the view files used in a single controller class. ControllerID here refers to the ID of the controller. It can be customized via CController::viewPath.
WebRoot/protected/views/layouts: This directory places all layout view files. It can be customized via CWebApplication::layoutPath.
WebRoot/protected/views/system: This directory contains all system view files. System view files are templates used to display exceptions and errors. It can be customized via CWebApplication::systemViewPath.
WebRoot/assets: This directory contains public resource files. Resource files are private files that can be published and accessed by web users. This directory must be writable by 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 via CThemeManager::basePath.
6. Database
Most web applications are driven by databases. We recommend using the following naming convention when naming tables and columns. Note that these specifications are not required for Yii.
㈠Database table names and column names are named in lowercase.
㈡Words in the name should be separated by underscores (e.g. product_order).
㈢For table names, you can use either singular or plural. But don't use both at the same time. For simplicity, we recommend using singular names.
㈣Table names can use a common prefix, such as tbl_. This is particularly useful when the table used by an application coexists in the same database as a table used by another application. The tables of these two applications can be easily distinguished by using different table prefixes.

Ⅱ. Using forms
When processing forms in Yii, the following steps are usually required:
1. Create a model class that represents the data fields to be collected.
2. Create a controller action to respond to form submission.
3. Create a form related to the controller action in the view script.
1. Create the model
Before writing the HTML code required for the form, we should first determine the type of data input from the end user, and what rules this data should conform to. Model classes can be used to record this information. As defined in the Models chapter, models are the central location for storing user input and validating those inputs.
Depending on how the data entered by the user is used, we can create two types of models. If user input is collected, used and then discarded, we should create a form model; if user input is collected and then saved to a 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 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 username and password entered by the user, and also have the option if the user wants to remember his login. Since $rememberMe has a default value of false, the corresponding option will be unchecked when initially displayed in the login form.
We call these member variables attributes instead of properties to distinguish them from ordinary properties. An attribute is a property 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 ensure that the user's input is valid before use. This is achieved by validating the user's input against 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 value
              array('password', 'authenticate'), // password should be authenticated
);
}

public function authenticate($attribute,$params)
{
_identity=new UserIdentity($this->username,$this->password ; ) Each rule returned must be in the following format:
array('AttributeList', 'Validator', 'on'=>'ScenarioList', ... additional options)
where:
AttributeList (attribute list) is required to pass A string of feature list that this rule validates, with each feature name separated by commas;
Validator (validator) specifies the type of validation to be performed;
on parameter is optional and specifies the list of scenarios to which this rule should be applied;
The additional option is an array of name-value pairs used to initialize the property values ​​of the corresponding validator.

There are three ways to specify Validator in validation rules:
First, Validator can be the name of a method in the model class, just like authenticate in the example above. The validation method must have the following structure:

public function validator name ($attribute, $params) { ... }
Second, Validator can be the name of a validator class. When this rule is applied, a validator Instances of the handler class will be created to perform the actual validation. Additional options in the rules are used to initialize the instance's property values. Validator classes must inherit from CValidator.
Third, Validator can be an alias of a predefined validator class. In the example above, the required name is an alias for CRequiredValidator, which is used to ensure that the property value being validated is not null. Here is the full list of predefined validator aliases:
boolean: Alias ​​for CBooleanValidator, ensuring that the attribute has a CBooleanValidator::trueValue or CBooleanValidator::falseValue value.
captcha: Alias ​​for CCaptchaValidator, ensures that the characteristic value is equal to the verification code displayed in the CAPTCHA.
compare: Alias ​​for CCompareValidator, ensures that a property is equal to another property or constant.
email: Alias ​​for CEmailValidator, ensures that the attribute is a valid email address.
default: Alias ​​of CDefaultValueValidator, specifying the default value of the attribute.
exist: Alias ​​for CExistValidator, ensures that the attribute value can be found in the column of the specified table.
file: Alias ​​for CFileValidator, make sure the attribute contains the name of an uploaded file.
filter: Alias ​​of CFilterValidator, changes this property through a filter.
in: Alias ​​for CRangeValidator, ensuring data is within a pre-specified value range.
length: Alias ​​of CStringValidator, ensuring that the length of data is within a specified range.
match: Alias ​​of CRegularExpressionValidator, ensuring that the data can match a regular expression.
numerical: Alias ​​of CNumberValidator, ensuring the data is a valid number.
required: Alias ​​for CRequiredValidator, ensuring the attribute is not empty.
type: Alias ​​of CTypeValidator, ensures that the attribute is of the specified data type.
unique: Alias ​​of CUniqueValidator, ensuring that data is unique among columns in the data table.
url: Alias ​​of CUrlValidator, ensures the data is a valid URL.

Below we list a few examples using only these predefined validators:
// Username is required
array('username', 'required'),
// Username must be between 3 and 12 characters between
array('username', 'length', 'min'=>3, 'max'=>12),
// In the registration scenario, the password password must be consistent with password2.
array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
// In the login scenario, the password must be verified.
array('password', 'authenticate', 'on'=>'login'),

3. Secure attribute assignment
After an instance of a class is created, we usually need to fill it with data submitted by the end user its characteristics. This can be easily achieved with a massive assignment like this:
$model=new LoginForm;
if(isset($_POST['LoginForm']))
$model->attributes=$_POST['LoginForm'] ;
The last expression is called a massive assignment, and it copies each item in $_POST['LoginForm'] to the corresponding model attribute. This is equivalent to the following assignment method:
foreach($_POST['LoginForm'] as $name=>$value)
{
 if($name is a safe feature)
   $model->$name=$value ;
}
The security of detection features is very important. For example, if we expose the primary key of a table thinking that it is safe, then the attacker may get an opportunity to modify the primary key of the record, thereby tampering with information that is not authorized to him. content.
Features are considered safe if they appear in a verification rule in the corresponding scenario. For example:
array('username, password', 'required', 'on'=>'login, register'),
array('email', 'required', 'on'=>'register'),
As shown above, the username and password attributes are required in the login scenario. The username, password and email attributes are required in the register scenario. So, if we perform block assignment in the login scenario, only username and password will be block assigned. Because they are the only ones that appear in login's validation rules. On the other hand, if the scenario is register, all three properties can be block assigned.
// In the login scenario
$model=new User('login');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
// In the registration scenario
$model=new User('register');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
Then Why do we use such a strategy to detect whether a feature is safe? The rationale behind this is: if a feature already has one or more validation rules that can detect validity, then what do we have to worry about?
Please remember that validation rules are used to check the data entered by the user, not the data we generated in the code (e.g. timestamp, automatically generated primary key). Therefore, do not add validation rules for features that do not accept end-user input.
Sometimes, we want to declare a feature to be safe even if we don't specify any rules for it. For example, the content of an article can accept any input from the user. We can do this using a special safe rule:
array('content', 'safe')
There is also an unsafe rule for declaring a property unsafe:
array('permission', 'unsafe')
The unsafe rule is not commonly used and is an exception to the safety properties we defined earlier.
4. Trigger validation
Once the model is populated with user-submitted data, we can call CModel::validate() to trigger the data validation process. This method returns a value indicating whether the verification was successful. For CActiveRecord models, validation can also be triggered automatically when we call its CActiveRecord::save() method.
We can set the scenario properties by setting the scenario attribute, so that the validation rules of the corresponding scenario will be applied.
Verification is performed based on scenarios. The scenario attribute specifies the scenario the model is currently used for and the set of validation rules currently used. For example, in the login scenario, we only want to validate the username and password inputs in the user model; while in the register scenario, we need to validate more inputs, such as email, address, etc. The following example demonstrates how to perform validation in the register scenario:
// Create a User model in the registration scenario. Equivalent to:
// $model=new User;
// $model->scenario='register';
$model=new User('register'); //Add parameters to the model class, which are Validation scenario to be triggered
// Fill the input value into the model
$model->attributes=$_POST['User'];
// Perform verification
if($model->validate()) // If the input is valid
                                                                                                                        The scenario can be specified through the on option in the rule. If the on option is not set, this rule applies to all scenarios. For example:
public function rules()
{
return array(
array('username, password', 'required'),
array('password_repeat', 'required', 'on'=>'register'),
        array('password', 'compare', 'on'=>'register'),
  );
}
The first rule will apply to all scenarios, while the second one will only apply to the register scenario.
5. Extract verification errors
After verification is completed, any errors that may occur will be stored in the model object. We can extract these error messages by calling CModel::getErrors() and CModel::getError(). The difference between these two methods is that the first method will return error information for all model properties, while the second method will only return error information for the first one.
6. Feature labels
When designing a form, we usually need to display a label for each form field. The label tells the user what information he should fill in this form field. Although we can hardcode a label in the view, it is more flexible and convenient if we specify (the label) in the corresponding model.
By default CModel will simply return the name of the attribute as its label. This can be customized by overriding the attributeLabels() method. As we will see in the next section, specifying tags in the model will allow us to create more powerful forms faster.

2. Create Actions
With the model in hand, we can start writing the logic for operating this model. We put this logic in a controller action. For the login form example, the corresponding code is:
public function actionLogin()
{
 $model=new LoginForm;
 if(isset($_POST['LoginForm']))
 {
                                                       Data
          $model->attributes=$_POST['LoginForm'];
                                   use using using ‐ ‐           ‐   ‐ ‐ ‐ ‐ ‐                                                                 using using using using data
        through out through ’'s' out's ‐ ‐ to ‐‐‐‐‐‐‐‐ and $this->redirect(Yii::app()->user->returnUrl); //Redirect to the page URL that previously required authentication
}
//Display the login form
$this->render ('login',array('model'=>$model));
}

As shown above, we first create a LoginForm model example; if the request is a POST request (meaning that the login form is submitted ), we populate $model with the submitted data $_POST['LoginForm']; then we validate this input, and if the validation is successful, redirect the user's browser to the page that previously required authentication. If the verification fails, or this action is accessed for the first time, we render the login view. The content of this view will be explained in the next section.
Tips: In the login action, we use Yii::app()->user->returnUrl to obtain the page URL that previously required authentication. The component Yii::app()->user is a CWebUser (or its subclass) that represents user session information (e.g. username, status).
Let us pay special attention to the following PHP statement that appears in the login action:
$model->attributes=$_POST['LoginForm'];
As we said in Safe Attribute Assignment, this line of code uses the user The submitted data populates the model. The attributes property is defined by CModel, which accepts an array of name-value pairs and assigns each value to the corresponding model attribute. So if $_POST['LoginForm'] gives us an array like this, the above code is equivalent to the following lengthy paragraph (assuming all the required attributes are present in the array):
$model->username =$_POST['LoginForm']['username'];
$model->password=$_POST['LoginForm']['password'];
$model->rememberMe=$_POST['LoginForm'] ['rememberMe'];
Note: In order for $_POST['LoginForm'] to pass us an array instead of a string, we need to follow a convention when naming form fields. Specifically, we name the form field corresponding to feature a in model class C, C[a]. For example, we can use LoginForm[username] to name the form field corresponding to the username attribute.
Now all that’s left is to create the login view, which should contain an HTML form with the required inputs.

三、创建表单
编写 login 视图是很简单的,我们以一个 form 标记开始,它的 action 属性应该是前面讲述的 login 动作的URL。然后我们需要为 LoginForm 类中声明的属性插入标签和表单域。最后,我们插入一个可由用户点击提交此表单的提交按钮。所有这些都可以用纯HTML代码完成。
Yii 提供了几个助手(helper)类简化视图编写。例如,要创建一个文本输入域,我们可以调用 CHtml::textField();要创建一个下拉列表,则调用 CHtml::dropDownList()。
例如, 如下代码将生成一个文本输入域,它可以在用户修改了其值时触发表单提交动作。
CHtml::textField($name,$value,array('submit'=>''));
下面,我们使用 CHtml 创建一个登录表单。我们假设变量 $model 是 LoginForm 的实例。



 
   
 
   

       
       
   

 
   

       
       
   

 
   

       
       
   

 
   

       
   

 



上述代码生成了一个更加动态的表单,例如, CHtml::activeLabel() 生成一个与指定模型的特性相关的标签。如果此特性有一个输入错误,此标签的CSS class 将变为 error,通过 CSS 样式改变了标签的外观。相似的, CHtml::activeTextField() 为指定模型的特性生成一个文本输入域,并会在错误发生时改变它的 CSS class。
我们还可以使用一个新的小物件 CActiveForm 以简化表单创建。这个小物件可同时提供客户端及服务器端无缝的、一致的验证。使用 CActiveForm, 上面的代码可重写为:

beginWidget('CActiveForm'); ?>
 
   errorSummary($model); ?>
 
   

       label($model,'username'); ?>
       textField($model,'username') ?>
   

 
   

       label($model,'password'); ?>
       passwordField($model,'password') ?>
   

 
   

       checkBox($model,'rememberMe'); ?>
       label($model,'rememberMe'); ?>
   

 
   

       
   

 
endWidget(); ?>


4. Collect form input
Sometimes we want to collect user input through batch mode. That is, users can enter information for multiple model instances and submit them all at once. We call this tabular input because these inputs are usually presented as HTML tables.
To use table input, we first need to create or populate an array of model instances, depending on whether we want to insert or update data. We then extract the user-entered data from the $_POST variable and assign it to each model. The slight difference from single model input is that we need to use $_POST['ModelClass'][$i] to extract the input data instead of using $_POST['ModelClass'].
public function actionBatchUpdate()
{
// Assuming each item is an instance of the 'Item' class,
// Extract the items to be updated in batch mode
$items=$this->getItemsToUpdate() ;
if(isset($_POST['Item']))
{
$valid=true;
foreach($items as $i=>$item)
{
if(isset($_POST['Item' ][$i]))
                        $item->attributes=$_POST['Item']                                                                                                                                                           ; $items));
}

With this action ready, we need to continue working on the batchUpdate view to display the input items in an HTML table.




$item): ?>


The above is the content of Yii Quick Start (1). For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!




Related labels:
yii
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Name PriceCountDescription