ThinkPHP- 31

PHP中文网
PHP中文网Original
2016-07-30 13:31:571110browse

Basics:

1. Basic concepts

LAMP

LAMP is an open resource network development platform based on Linux, Apache, MySQL and PHP. The term comes from Europe, where these programs were commonly used as a standard development environment. The name is derived from the first letter of each program. Each program adheres to open source standards in its ownership: Linux is an open system; Apache is the most versatile web server; MySQL is a relational database with additional tools for web-based administration; PHP is a popular object scripting language that includes It has many of the best features of other languages ​​to make web development more efficient. Developers using these tools in the Linux environment under the Windows operating system are called using WAMP.
Although these open source programs themselves are not specifically designed to work with several other programs, because they are all influential open source software and share many common characteristics, these components are often used together. Over the past few years, the compatibility of these components has continued to improve, and their use together has become more common. And they have created certain extensions to improve collaboration between different components. Currently, these products are included by default in almost all Linux distributions. Linux operating system, Apache server, MySQL database and Perl, PHP or Python language, these products together form a powerful web application platform.
With the vigorous development of the open source trend, open source LAMP has formed a three-legged trend with J2EE and .Net commercial software, and the software development project has a low investment cost in software, so it has attracted the attention of the entire IT community. In terms of website traffic, more than 70% of the access traffic is provided by LAMP. LAMP is the most powerful website solution.


OOP

Object Oriented Programming (OOP, object-oriented programming) is a computer programming architecture. A basic principle of OOP is that a computer program is composed of a single unit or object that functions as a subroutine. OOP achieves three main goals of software engineering: reusability, flexibility, and extensibility. In order to realize the overall operation, each object can receive information, process data and send information to other objects. OOP mainly has the following concepts and components:
Component - a unit where data and functions are formed together in a running computer program. Components are the basis of modules and structures in OOP computer programs.
Abstractness - The program has the ability to ignore certain aspects of the information being processed, that is, the ability to focus on the main aspects of the information.
Encapsulation - also called information encapsulation: ensure that components will not change the internal state of other components in unexpected ways; only those components that provide internal state changing methods can access their internal state. Each type of component provides an interface to communicate with other components and specifies methods for other components to call.
Polymorphism - Component references and class assemblies involve many other different types of components, and the results generated by referencing components must be based on the actual call type.
Inheritance - Allows the creation of subclassed components based on existing components, which unifies and enhances polymorphism and encapsulation. Typically, classes are used to group components, and new classes can also be defined as extensions of existing classes, so that classes can be organized into a tree or network structure, which reflects the versatility of actions.
Component-based programming has become particularly popular in scripting languages ​​due to reasons such as abstraction, encapsulation, reusability, and ease of use.


MVC

MVC is a design pattern that enforces separation of input, processing, and output of an application. Applications using MVC are divided into three core components: model (M), view (V), and controller (C), each of which handles its own tasks.
View: A view is the interface that users see and interact with. For old-fashioned Web applications, the view is an interface composed of HTML elements. In new-style Web applications, HTML still plays an important role in the view, but some new technologies have emerged in endlessly, including Adobe Flash and Some markup languages ​​and Web services like XHTML, XML/XSL, WML, etc. How to deal with an application's interface is becoming more and more challenging. One of the big benefits of MVC is that it can handle many different views for your application. No real processing occurs in the view, whether the data is stored online or a list of employees. As a view, it just serves as a way to output the data and allow the user to manipulate it.
Model: Model represents enterprise data and business rules. Among the three components of MVC, the model has the most processing tasks. For example, it might use component objects like EJBs and ColdFusion Components to handle databases. The data returned by the model is neutral, which means that the model has nothing to do with the data format, so that a model can provide data for multiple views. Code duplication is reduced because the code applied to the model only needs to be written once and can be reused by multiple views.
Controller: The controller accepts user input and calls models and views to complete the user's needs. So when a hyperlink in a Web page is clicked and an HTML form is sent, the controller itself does not output anything or do any processing. It just receives the request and decides which model component to call to handle the request, and then determines which view to use to display the data returned by the model processing.
Now we summarize the MVC processing process. First, the controller receives the user's request and decides which model should be called for processing. Then the model uses business logic to process the user's request and returns the data. Finally, the controller formats the model with the corresponding view. The data is returned and presented to the user through the presentation layer.


ORM

Object/Relation Mapping (ORM for short) was born with the development of object-oriented software development methods. The object-oriented development method is the mainstream development method in today's enterprise-level application development environment, and the relational database is the mainstream data storage system that permanently stores data in the enterprise-level application environment. Objects and relational data are two forms of expression of business entities. Business entities are represented as objects in memory and as relational data in the database. There are associations and inheritance relationships between objects in memory, but in the database, relational data cannot directly express many-to-many associations and inheritance relationships. Therefore, object-relational mapping (ORM) systems generally exist in the form of middleware, which mainly implements the mapping of program objects to relational database data.
Object-oriented is developed based on the basic principles of software engineering (such as coupling, aggregation, encapsulation), while relational database is developed from mathematical theory. There are significant differences between the two sets of theories. In order to solve this mismatch phenomenon, object relational mapping technology came into being.


AOP

AOP (Aspect-Oriented Programming, aspect-oriented programming) can be said to be the supplement and improvement of OOP (Object-Oriented Programming, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to establish an object hierarchy to simulate a collection of common behaviors. When we need to introduce public behavior to dispersed objects, OOP is powerless. In other words, OOP allows you to define relationships from top to bottom, but it is not suitable for defining relationships from left to right. For example, the logging function. Logging code tends to be spread horizontally across all object hierarchies, having nothing to do with the core functionality of the objects it's spread to. The same is true for other types of code, such as security, exception handling, and transparent persistence. This kind of irrelevant code scattered everywhere is called cross-cutting code. In OOP design, it leads to the duplication of a large amount of code and is not conducive to the reuse of various modules. AOP technology is just the opposite. It uses a technology called "cross-cutting" to dissect the inside of the encapsulated object and encapsulate the public behaviors that affect multiple classes into a reusable module. Its name is "Aspect", which means aspect. The so-called "aspect", simply put, is to encapsulate the logic or responsibilities that have nothing to do with the business but are commonly called by the business modules, so as to reduce the duplication of code in the system, reduce the coupling between modules, and benefit the future. operability and maintainability. AOP represents a horizontal relationship. If the "object" is a hollow cylinder, which encapsulates the properties and behavior of the object, then the aspect-oriented programming method is like a sharp knife, cutting these hollow cylinders into The body is cut open to obtain information about its interior. The cut section is the so-called "aspect". Then it restored these cut sections with uncanny skills, leaving no trace.
Using "cross-cutting" technology, AOP divides the software system into two parts: core concerns and cross-cutting concerns. The main process of business processing is the core concern, and the part that has little relationship with it is the cross-cutting concern. One characteristic of cross-cutting concerns is that they often occur in multiple places within the core concern, and are essentially similar everywhere. Such as authority authentication, logging, and transaction processing. The role of Aop is to separate various concerns in the system, separating core concerns and cross-cutting concerns. As Adam Magee, senior solution architect at Avanade, said, the core idea of ​​AOP is to "separate the business logic in the application from the common services that support it." ”


CURD

CURD is an abbreviation in database technology. The basic functions of various parameters in general project development are CURD. It represents Create, Update, Read and Delete operations. CURD defines basic atomic operations for processing data. The reason why CURD is elevated to the level of a technical difficulty is that the performance of completing an aggregation-related activity involving CURD operations in multiple database systems may vary greatly as the data relationships change.
CURD does not necessarily use the create, update, read and delete methods in specific applications, but the functions they complete are the same. For example, ThinkPHP uses the add, save, select, and delete methods to represent the CURD operations of the model.


ActiveRecord

Active Record (Chinese name: Active Record) is a domain model pattern, characterized by a model class corresponding to a table in a relational database, and an instance of the model class corresponding to a row of records in the table . Active Record and Row Gateway are very similar, but the former is a domain model and the latter is a data source model. Relational databases often express entity relationships through foreign keys, and Active Record also maps this relationship to object association and aggregation at the data source level. Active Record is suitable for very simple domain requirements, especially when the domain model and database model are very similar. If you encounter a more complex domain model structure (such as a domain model using inheritance and strategy), you often need to use a domain model that separates data sources and combine it with a Data Mapper.
Active Record driver framework generally has the functions of ORM framework, but Active Record is not a simple ORM, just like the difference from Row Gateway. First proposed by Rails, it follows the standard ORM model: tables map to records, records map to objects, and fields map to object properties. With the following naming and configuration conventions, the operation of the model can be realized quickly to a large extent, and it is concise and easy to understand.


Single entrance

Single entry usually means that a project or application has a unified (but not necessarily unique) entry file, which means that all functional operations of the project are performed through this entry file, and the entry file is often the first step. executed.
The advantage of a single entrance is that the overall project is relatively standardized, because the same entrance often has the same rules for different operations. Another aspect is that the benefit of a single entrance is that the control is more flexible, because interception is convenient, and judgments and operations such as some permission controls and user logins can be handled uniformly.
Some people may worry about whether all websites are accessed through one entry file, which will cause too much pressure. In fact, this is an unfounded idea.

2. Directory structure


Directory/File Description
ThinkPHP.php Framework entry file
Common Framework public file directory
Conf Framework configuration file directory
Lang Framework system language directory
Lib System core base class library directory
Tpl System template directory
Extend Framework extension directory (about For detailed information about the extended directory, please refer to the extended chapter later)

Note: If you download the core version, the Extend directory may be empty, because ThinkPHP itself does not rely on any extensions.



3. Naming conventions

When developing with ThinkPHP, you should try to follow the following naming conventions:

  • Class files are all suffixed with .class.php (this refers to the internal use of ThinkPHP class library file, does not represent an externally loaded class library file), use camel case naming, and the first letter is capitalized, such as DbMysql.class.php;

  • Make sure that the naming of the file and the calling case are consistent, because in the class On Unix systems, it is case-sensitive (ThinkPHP, in debug mode, will strictly check capitalization even on Windows platforms);

  • The class name and the file name are consistent (including the above-mentioned consistent case), for example The file name of the UserAction class is UserAction.class.php, the file name of the InfoModel class is InfoModel.class.php, and the class naming of different class libraries has certain standards;

  • functions, configuration files and other class library files Others generally have a .php suffix (there is no requirement for those introduced by third parties);

  • functions are named using lowercase letters and underscores, such as get_client_ip;

  • methods are named using camel case, and The first letter is lowercase or the underscore "_" is used, such as getUserName, _parseType. Usually methods starting with an underscore are private methods;

  • attributes are named using camel case, and the first letter is lowercase or the underscore "_" is used, such as tableName , _instance, usually attributes starting with an underscore are private attributes;

  • Functions or methods starting with a double underscore "__" are used as magic methods, such as __call and __autoload;

  • Constant names are named with capital letters and underscores , such as HAS_ONE and MANY_TO_MANY;

  • Configuration parameters are named with uppercase letters and underscores, such as HTML_CACHE_ON;

  • Language variables are named with uppercase letters and underscores, such as MY_LANG, language variables starting with underscores are usually used for system language variables , such as _CLASS_NOT_EXIST_;

  • There is no mandatory specification for the naming of variables, and it can be done according to team specifications;

  • ThinkPHP’s template file defaults to .html as the suffix (can be modified through configuration);

  • Data tables and fields are named in lowercase and underlined, and be careful not to start field names with an underscore, such as the think_user table and user_name field. Data table fields like _username may be filtered.


In ThinkPHP, there is a special case of function naming, which is a single-letter uppercase function. Such functions are usually shortcut definitions of certain operations, or have special functions. For example, ADSL method and so on.

Another very important point is that ThinkPHP uses UTF-8 encoding by default, so please ensure that your program files are saved in UTF-8 encoding format and remove the BOM information header (there are many ways to remove BOM header information, different editors There are setting methods, and you can also use tools for unified detection and processing), otherwise it may cause many unexpected problems.


4. CBD Architecture

ThinkPHP3.0 version introduces a new CBD (Core + Behavior + Driver) architecture model, because from the bottom, the framework adopts the core + behavior + driver architecture system. The most critical parts are retained, and labels are set at important locations for marking. Other functions are combined using behavioral extensions and drivers. Developers can extend or replace a certain label position based on their own needs. You can easily customize the bottom layer of the framework, and you can also add your own label positions and application rows in the application layer. The label position is similar to the "aspect" in the AOP concept, and the behaviors are programmed around this "aspect". If the system's built-in core extension is regarded as a standard mode, then users can use this All behavior customization is packaged into a new pattern, so in ThinkPHP, it is called pattern extension. In fact, pattern extension can not only replace and add behaviors, but also replace and modify the underlying MVC to achieve customized Customization purposes. Using this new feature, developers can easily customize a development framework for themselves or their companies through pattern extensions. The new version of pattern extensions is the master of framework extensions and creates a new milestone. This is exactly That’s the real beauty of the new version.

5. Development process

The general development process for creating applications using ThinkPHP is:

  • System design, creating databases and data tables; (optional)

  • Name the project and create the project entry file, and turn on debugging mode ;

  • Complete the project configuration;

  • Create the project function library; (Optional)

  • Develop the extensions needed for the project (mode, driver, tag library, etc.); (Optional)

  • Create Controller class;

  • Create model class; (optional)

  • Create template file;

  • Run and debug, analyze logs;

  • Develop and set up cache functionality; (Optional)

  • Add routing support; (Optional)

  • Security checks; (Optional)

  • Deploy to production.


6. Entry file

ThinkPHP adopts a single entry mode for project deployment and access. No matter what function is completed, a project has a unified (but not necessarily the only) entry. It should be said that all projects start from the entry file, and the entry files of all projects are similar. The entry file mainly includes:

  • Define the framework path, project path and project name (optional)

  • Define related constants for debugging mode and running mode (optional)

  • Load the framework entry file (required)


7. Project directory

The generated project directory structure is similar to the system directory, including :

Directory Description
Common Project public file directory, which generally places the project’s public functions
Conf Project configuration directory, all project configuration files are placed here
Lang Project language pack directory (optional, can be deleted if multi-language support is not required)
Lib Project class library directory, usually including Action and Model subdirectories
Tpl Project template directory , supports template themes
Runtime project runtime directory, including Cache (template cache), Temp (data cache), Data (data directory) and Logs (log file) subdirectories, if there are groups, first Is a group directory.

If you need to move index.php outside the App directory, you only need to add the project name and project path definition to the entry file.

  1. 031eb56b70fbf6052288d4495655241e 'Index', // Default module

  2. 'URL_MODEL' => '2', //URL mode

  3. 'SESSION_AUTO_START' => true, //Whether to open session

  4. //More configuration parameters

  5.                                                                                                 ); To configure more information, for example:

  6. //项目配置文件
     return array(
        'DEFAULT_MODULE'     => 'Index', //默认模块
        'URL_MODEL'          => '2', //URL模式
        'SESSION_AUTO_START' => true, //是否开启session
        'USER_CONFIG'        => array(
            'USER_AUTH' => true,
            'USER_TYPE' => 2,
        ),
        //更多配置参数
        //...
     );

  7. It should be noted that the secondary parameter configuration is case-sensitive, which means that the reading must be consistent with the definition.



9. Conventional configuration and project configuration, debugging configuration

    Convention is more important than configuration is an important idea that the system follows. The system has a built-in convention configuration file (Confconvention.php located under the system directory). Common parameters are configured by default according to most uses.
  1. The project configuration file is the most commonly used configuration file. The project configuration file is located under the project's configuration file directory Conf, and the file name is config.php.
In addition to adding built-in parameter configurations in the project configuration file, you can also add additional configuration parameters required by the project.

If the application state is not configured, the system defaults to the debug state, which means the default configuration parameters are:

'APP_STATUS' => 'debug', //应用调试模式状态

The debug.php configuration file only needs to configure different parameters from the project configuration file and system debugging configuration file or new parameters.

If you want to add application status under debug mode, such as test status, you can change the settings in the project configuration file as follows:


'APP_STATUS' => 'test', //应用调试模式状态

    Since debug mode does not have any cache, it involves more File IO operations and templates are compiled in real time, so when debugging mode is turned on, performance will decrease to a certain extent, but it will not affect the performance of deployment mode.

  1. Note: Once debugging mode is turned off, the project’s debugging configuration file will become invalid immediately.

  1. 10. Group configuration and read configuration, dynamic configuration

    If module grouping is enabled, you can define the configuration file separately for each group, and the group configuration file is located at:
  2. Project configuration directory/group Name/config.php
    You can enable grouping through the following configuration:
  3. 'APP_GROUP_LIST' => 'Home,Admin', //项目分组设定
     'DEFAULT_GROUP'  => 'Home', //默认分组

Now that two groups, Home and Admin, are defined, we can define the grouping configuration file as follows:


Conf/Home/config.php
Conf/Admin/config.php

The configuration file of each group is only Valid in the current group, the definition format of the group configuration is the same as the project configuration.

Note: Group names are case-sensitive and must be consistent with the defined group name.


After defining the configuration file, you can use the C method provided by the system (if you feel it is strange, you can use the Config word to help remember) to read the existing configuration:

  1. C ('parameter name') //Get the parameter value that has been set


For example, C('APP_STATUS') can read the setting value of the system's debug mode. If APP_STATUS does not yet have a setting, NULL is returned.



C method can also be used to read two-dimensional configuration:

  1. C('USER_CONFIG.USER_TYPE')//Get the user type settings in the user configuration

because the configuration parameters are globally valid , so the C method can read any configuration anywhere, even if a certain setting parameter has expired.


In the specific Action method, we can still dynamically configure certain parameters, mainly those parameters that have not been used yet.
Set a new value:

  1. C('Parameter name','New parameter value');

For example, if we need to dynamically change the validity period of the data cache, we can use

  1. C(' DATA_CACHE_TIME','60');


can also support the reading and setting of two-dimensional arrays, using dot syntax for operations, as follows:
Get the parameter value that has been set:

  1. C(' USER_CONFIG.USER_TYPE');

Set a new value:

  1. C('USER_CONFIG.USER_TYPE','1');


Starting from version 3.1, the C function supports the configuration saving function. Only valid for batch settings, usage method:

  1. C($array,'name');

where array is an array variable, which will save the configuration parameter list after batch settings to the cache data identified by name In
, you can use

  1. C('','name'); //or C(null,'name'); to get the cached setting list data.

will read the cache configuration data identified by name to Current configuration data (merged).



11. Extended configuration

The project configuration file will be included in the compilation cache during deployment mode, which means that modifying the project configuration file after compilation will not take effect immediately. You need to delete the compilation cache to take effect. . Extended configuration files are not affected by this restriction. Even in deployment mode, modified configurations can take effect in real time, and the configuration format is the same as the project configuration.
The way to set the extended configuration is as follows (multiple files are separated by commas):

  1. 'LOAD_EXT_CONFIG' => 'user,db', // Load the extended configuration file

The project is set to load the extended configuration file user .php and db.php are used for user configuration and database configuration respectively, then the configuration files Conf/user.php and Conf/db.php under the project configuration directory will be automatically loaded.

If you want to use the secondary configuration method, you can set it as follows:

  1. 'LOAD_EXT_CONFIG' => array(

  2. 'USER' => 'user', //User configuration

  3. 'DB ' => 'db', //Database configuration

  4. ), //Load the extended configuration file

The same user.php configuration file content, but the final method of obtaining user parameters becomes:

  1. C('USER.USER_AUTH_ID');

This method can avoid parameter conflict problems in large project situations.


Some configuration files below have been used by the system, please do not redefine them as custom extended configurations:

File name Description
config.php Project configuration file
tags.php Project behavior configuration file
alias.php Project alias definition file
debug.php Project debug mode configuration file (and the configuration file corresponding to APP_STATUS set by the project)
core.php The core compilation list file added to the project (the core compilation list will not be overwritten)


12. Function library


The function library in ThinkPHP can be divided into system function library and project function library.


System function library

Library The system function library is located under the Common directory of the system and has three files:
common.php is a basic function library that must be loaded globally and can be called directly at any time;
functions.php It is the public function library of the framework standard mode. Other modes can replace and load their own public function library or redefine the functions in the public function library;
runtime.php is the framework runtime file, which is only used in debugging mode or compilation process. is loaded, so the methods in it cannot be called directly in the project;


Project function library

Library The project function library is usually located under the Common directory of the project, and the file name is common.php. This file will be executed during execution. Automatically loaded and merged into the project compilation unified cache. If the group deployment method is used and the "group name/function.php" file exists in the directory, it will also be automatically loaded according to the execution of the current group. Therefore, the project function library All functions can also be used directly without manual loading.
If dynamic function loading configuration is used in the project configuration, there may be more function files under the project Common directory, and dynamically loaded function files will not be included in the compilation cache.
In special cases, the mode can change the location or name of the automatically loaded project library.


Extended function library

Library We can define an extended function library under the project's public directory to facilitate loading and calling when needed. The function definition specifications of the extended function library are the same as those of the project function library, except that the function library file name can be named arbitrarily. Generally speaking, the extended function library will not be automatically loaded unless you set up dynamic loading.


Function loading

The functions in the system function library and project function library can be called directly without loading. For the project's extended function library, the following two methods can be used to call:
Dynamic loading
We can call it in the project Define the LOAD_EXT_FILE parameter in the configuration file, for example:

  1. "LOAD_EXT_FILE"=>"user,db"

Through the above settings, the extended function library file under the project's public directory will be automatically loaded during execution. user.php and db.php, so that you can directly call the functions in the extended function library user.php and db.php in the project, and the function modifications in the extended function library take effect in real time.
Manual loading
If your function is only used occasionally by individual modules, you do not need to use automatic loading. You can use the load method to load it manually when it needs to be called. The method is as follows:

  1. load("@.user" )

@.user means loading the user function file of the current project, so that the functions in the user.php function library can be directly extended.


13. Class library

ThinkPHP’s class library includes base class library and application class library. The system’s class library naming rules are as follows:

Class library Rules Example
Control Device class Module name+Action For example UserAction, InfoAction
Model class Model name+Model For example UserModel, InfoModel
Behavior class Behavior name+Behavior For example CheckRouteBehavior
Widget class Widget name+Widget For example, BlogInfoWidget
Driver class Engine name + driver name For example, DbMysql represents the mysql database driver, CacheFile represents the file cache driver

Base class library

Base class library refers to the system class library that complies with the ThinkPHP class library specifications, including ThinkPHP's core base class library and extended base class library. The core base class library directory is located in the Lib directory of the system. The core base class library is also the Think class library. The extended base class library is located in the Extend/Library directory and can extend ORG and Com extended class libraries. The role of the core base class library is to complete the basic classes and built-in support classes necessary to complete the universal development of the framework, including:

Directory Calling path Description
Lib/Core Think .Core Core library package
Lib/Behavior Think.Behavior Built-in behavior library package
Lib/Driver Think.Driver Built-in driver library package
Lib/Template Think.Template Built-in template engine library package

The core class library package contains the following core class libraries:

Class name Description
Action System basic controller class
App System application class
Behavior System behavior basic class
Cache System cache class
Db System abstract database class
Dispatcher URL dispatch class
Log System log class
Model System basic model class
Think System entry and static class
ThinkException System basic exception class
View View class
Widge t System Widget basic class

Application class library

Application class library refers to the class library that is defined or used in the project. These class libraries also follow the naming convention of ThinkPHP. The application library directory is located in the Lib directory under the project directory. Application libraries have a wide range, including Action libraries, Model libraries or other tool libraries, usually including:

Directory Calling path Description
Lib/Action @. Action or automatically load the controller class library package
Lib/Model @.Model or automatically load the model class library package
Lib/Behavior Use the B method to call or automatically load Apply behavior class library package
Lib/Widget Use W method to call in template Apply Widget class library package

项目根据自己的需要可以在项目类库目录下面添加自己的类库包,例如Lib/Common、Lib/Tool等。


类库导入

一、Import显式导入

ThinkPHP模拟了Java的类库导入机制,统一采用import方法进行类文件的加载。import方法是ThinkPHP内建的类库导入方法,提供了方便和灵活的文件导入机制,完全可以替代PHP的require和include方法。例如:

  1. import("Think.Util.Session");
     import("App.Model.UserModel");

import方法具有缓存和检测机制,相同的文件不会重复导入,如果导入了不同的位置下面的同名类库文件,系统也不会再次导入

注意:在Unix或者Linux主机下面是区别大小写的,所以在使用import方法的时候要注意目录名和类库名称的大小写,否则会导入失败。对于import方法,系统会自动识别导入类库文件的位置,ThinkPHP的约定是Think、ORG、Com包的导入作为基类库导入,否则就认为是项目应用类库导入。

  1. import("Think.Util.Session");
     import("ORG.Util.Page");

上面两个方法分别导入了Think基类库的Util/Session.class.php文件和ORG扩展类库包的Util/Page.class.php文件。

要导入项目的应用类库文件也很简单,使用下面的方式就可以了,和导入基类库的方式看起来差不多:

  1. import("MyApp.Action.UserAction");
     import("MyApp.Model.InfoModel");

上面的方式分别表示导入MyApp项目下面的Lib/Action/UserAction.class.php和Lib/Model/InfoModel.class.php类文件。


通常我们都是在当前项目里面导入所需的类库文件,所以,我们可以使用下面的方式来简化代码

  1. import("@.Action.UserAction");
     import("@.Model.InfoModel");



二,别名导入

除了命名空间的导入方式外,import方法还可以支持别名导入,要使用别名导入,首先要定义别名,我们可以在项目配置目录下面增加alias.php 用以定义项目中需要用到的类库别名,例如:

  1. return array(
        'rbac' =>LIB_PATH.'Common/Rbac.class.php',
        'page' =>LIB_PATH.'Common/Page.class.php',
     );

那么,现在就可以直接使用:

  1. import("rbac");
     import("page");

导入Rbac和Page类,别名导入方式禁止使用import方法的第二和第三个参数,别名导入方式的效率比命名空间导入方式要高效,缺点是需要预先定义相关别名。



导入第三方类库

第三方类库统一放置在系统扩展目录下的Vendor 目录,并且使用vendor 方法导入,其参数和 import 方法是 一致的,只是默认的值有针对变化。 例如,我们把 Zend 的 Filter\Dir.php 放到 Vendor 目录下面,这个时候 Dir 文件的路径就是 Vendor\Zend\Filter\Dir.php,我们使用vendor 方法导入只需要使用:

  1. Vendor('Zend.Filter.Dir');

就可以导入Dir类库了。
Vendor方法也可以支持和import方法一样的基础路径和文件名后缀参数,例如:

Vendor('Zend.Filter.Dir',dirname(__FILE__),'.class.php');

自动加载

在大多数情况下,我们无需手动导入类库,而是通过配置采用自动加载机制即可,自动加载机制是真正的按需加载,可以很大程度的提高性能。自动加载有三种情况,按照加载优先级从高到低分别是:别名自动加载、系统规则自动加载和自定义路径自动加载。

一、别名自动加载

在前面我们提到了别名的定义方式,并且采用了import方法进行别名导入,其实所有定义别名的类库都无需再手动加载,系统会按需自动加载。


二、 系统规则自动加载

果你没有定义别名的话,系统会首先按照内置的规则来判断加载,系统规则仅针对行为类、模型类和控制器类,搜索规则如下:

类名 规则 说明
行为类 规则1 搜索系统类库目录下面的Behavior目录
规则2 搜索系统扩展目录下面的Behavior目录
规则3 搜索应用类库目录下面的Behavior目录
规则4 如果启用了模式扩展,则搜索模式扩展目录下面的Behavior目录
模型类 规则1 如果启用分组,则搜索应用类库目录的Model/当前分组 目录
规则2 搜索应用类库下面的Model目录
规则3 搜索系统扩展目录下面的Model目录
控制器类 规则1 如果启用分组,则搜索应用类库目录的Action/当前分组 目录
规则2 搜索项目类库目录下面的Action目录
规则3 搜索系统扩展目录下面的Action目录

注意:搜索的优先顺序从上至下 ,一旦找到则返回,后面规则不再检测。如果全部规则检测完成后依然没有找到类库,则开始进行第三个自定义路径自动加载检测。



三、 自定义路径自动加载

当你的类库比较集中在某个目录下面,而且不想定义太多的别名导入的话,可以使用自定义路径自动加载方式,这种方式需要在项目配置文件中添加自动加载的搜索路径,例如:

'APP_AUTOLOAD_PATH' =>'@.Common,@.Tool',
  1. 表示,在当前项目类库目录下面的Common和Tool目录下面的类库可以自动加载。多个搜索路径之间用逗号分割,并且注意定义的顺序也就是自动搜索的顺序。


  2. 注意:自动搜索路径定义只能采用命名空间方式,也就是说这种方式只能自动加载项目类库目录和基类库目录下面的类库文件。



------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


控制器:

1. URL模式

传统方式的文件入口访问会变成由URL的参数来统一解析和调度。

ThinkPHP支持四种URL模式,可以通过设置URL_MODEL参数来定义,包括普通模式、PATHINFO、REWRITE和兼容模式。


一、普通模式:设置URL_MODEL 为0
采用传统的URL参数模式

  1. http://serverName/appName/?m=module&a=action&id=1


二、PATHINFO模式(默认模式):设置URL_MODEL 为1
默认情况使用PATHINFO模式,ThinkPHP内置强大的PATHINFO支持,提供灵活和友好URL支持。PATHINFO模式自动识别模块和操作,例如

http://serverName/appName/module/action/id/1/或者
http://serverName/appName/module,action,id,1/




三、REWRITE模式: 设置URL_MODEL 为2
该URL模式和PATHINFO模式功能一样,除了可以不需要在URL里面写入口文件,和可以定义.htaccess 文件外。在开启了Apache的URL_REWRITE模块后,就可以启用REWRITE模式了,具体参考下面的URL重写部分。

四、兼容模式: 设置URL_MODEL 为3
兼容模式是普通模式和PATHINFO模式的结合,并且可以让应用在需要的时候直接切换到PATHINFO模式而不需要更改模板和程序,还可以和URL_WRITE模式整合。兼容模式URL可以支持任何的运行环境。

兼容模式的效果是:

  1. http://serverName/appName/?s=/module/action/id/1/

并且也可以支持参数分割符号的定义,例如在URL_PATHINFO_DEPR为~的情况下,下面的URL有效:

  1. http://serverName/appName/?s=module~action~id~1

其实是利用了VAR_PATHINFO参数,用普通模式的实现模拟了PATHINFO的模式。但是兼容模式并不需要自己传s变量,而是由系统自动完成URL部分。正是由于这个特性,兼容模式可以和PATHINFO模式之间直接切换,而不需更改模板文件里面的URL地址连接。我们建议的方式是采用PATHINFO模式开发,如果部署的时候环境不支持PATHINFO则改成兼容URL模式部署即可,程序和模板都不需要做任何改动。


2. 模块和操作

http://域名/项目名/分组名/模块名/操作名/其他参数
Dispatcher会根据URL地址来获取当前需要执行的项目、分组(如果有定义的话)模块、操作以及其他参数,在某些情况下,项目名可能不会出现在URL地址中(通常情况下入口文件则代表了某个项目,而且入口文件可以被隐藏)。
每一个模块就是一个控制器类,通常位于项目的Lib\Action目录下面。

3.1版本开始,增加ACTION_SUFFIX配置参数,用于设置操作方法的后缀。
例如,如果设置:

  1. 'ACTION_SUFFIX'=>'Act'

那么访问某个模块的add操作对应读取模块类的操作方法则由原来的add方法变成addAct方法。



3. 定义控制器和空操作,空模块

一个应用如果不需要和数据库交互的时候可以不需要定义模型类,但是必须定义Action控制器,一般位于项目的Lib/Action目录下面。
Action控制器的定义非常简单,只要继承Action基础类就可以了,例如:

  1. Class UserAction extends Action{}

控制器文件的名称是UserAction.class.php。

Empty operation means that when the system cannot find the specified operation method, it will locate the empty operation (_empty) method to execute. Using this mechanism, we can realize the optimization of error pages and some URLs.

The concept of empty module means that when the system cannot find the specified module name, the system will try to locate the empty module (EmptyAction). We can use this mechanism to customize error pages and optimize URLs.


4. Module grouping

Configuration parameters related to module grouping include:

Configuration parameters Description
APP_GROUP_LIST Project grouping list (configuration means turning on grouping)
DEFAULT_GROUP Default group (default value is Home)
TMPL_FILE_DEPR The delimiter of modules and operations under the group template, the default value is “/”
VAR_GROUP The URL parameter name of the group, The default is g (required for normal mode URL)

For example, if we divide the current project into two groups, Home and Admin, which represent front-end and back-end functions respectively, then we only need to add the following configuration to the project configuration:

  1. 'APP_GROUP_LIST' => 'Home,Admin', //Project group setting

  2. 'DEFAULT_GROUP' => 'Home', //Default group

Multiple groups can be separated by commas. Only one default group is allowed to be set.



5. URL pseudo-static

ThinkPHP supports pseudo-static URL settings. You can add the static suffix you want at the end of the URL by setting the URL_HTML_SUFFIX parameter without affecting the normal execution of the current operation. For example, if we set

  1. 'URL_HTML_SUFFIX'=>'shtml'

, we can put the following URL

  1. http://serverName/Blog/read/id/1

Becomes

  1. http://serverName/Blog/read/id/1.shtml

The latter has more URL characteristics of a static page, but has the same execution effect as the previous URL and will not affect Use of original parameters.
Note: The pseudo-static suffix does not need to include the "." in the suffix when setting it. Therefore, the following configurations are actually equivalent:

  1. 'URL_HTML_SUFFIX'=>'.shtml'

After pseudo-static setting, if you need to dynamically generate a consistent URL, you can use the U method in the template file Generate URL.

Starting from version 3.1, by default, all static suffixes can be supported, and the current pseudo-static suffix will be recorded to the constant __EXT__, but it will not affect normal page access. If you want to get the current pseudo-static suffix, you can get it through the constant __EXT__.

If you just want to support the configured pseudo-static suffix, you can directly set it to support multiple suffixes, for example:

  1. 'URL_HTML_SUFFIX'=>'html|shmtl|xml' // Multiple use | split


If multiple pseudo-static suffixes are set, the first suffix will be used by default in the URL address generated using the U function. It also supports specifying a suffix to generate the URL address.


6. URL routing

ThinkPHP supports the URL routing function. To enable the routing function, you need to set the URL_ROUTER_ON parameter to true. After the routing function is enabled and the URL_ROUTE_RULES parameter is configured, the system will automatically detect the route. If a route name matching the current URL is found in the route definition, route parsing and redirection will be performed.

For details, please see: http://doc.thinkphp.cn/manual/url_route.html


7. URL rewriting

For details, please see: http://doc.thinkphp.cn/manual/url_rewrite. html

<code><code><code><code><code><code><code><code><code>

8. URL generation

<code><code><code><code><code><code><code><code><code>To match the URL pattern used , we need to be able to dynamically generate the corresponding URL address based on the current URL settings. To this end, ThinkPHP provides a built-in U method for dynamic generation of URLs, which can ensure that the project is not affected by the environment during the transplantation process. The definition rules of the
U method are as follows (the parameters in square brackets are determined according to the actual application):

  1. U('[Group/Module/Operation]?Parameters' [,' Parameters','pseudo-static suffix','whether to jump','display domain name'])

<code><code><code><code><code><code><code><code><code>If the project and module are not defined, it means the current project and module Name, here are some simple examples:

  1. U('User/add') // Generate the URL address of the add operation of the User module

  2. U( 'Blog/read?id=1') // Generate the read operation of the Blog module and the URL address with id 1

  3. U('Admin/User/select') // Generate the select operation of the User module of the Admin group The second parameter of the URL address

<code><code><code><code><code><code><code><code><code>U method supports two definition methods: array and string. If it is only a string parameter, it can be in the first parameter Definition, for example:

  1. U('Blog/cate',array('cate_id'=>1,'status'=>1))

  2. U('Blog/cate','cate_id=1&status=1')

  3. U('Blog/cate?cate_id=1&status=1')

<code><code><code><code><code><code><code><code><code>三种方式是等效的,都是 生成Blog模块的cate操作 并且cate_id为1 status为1的URL地址
但是不允许使用下面的定义方式来传参数

  1. U('Blog/cate/cate_id/1/status/1')

<code><code><code><code><code><code><code><code><code>

根据项目的不同URL设置,同样的U方法调用可以智能地对应产生不同的URL地址效果,例如针对

  1. U('Blog/read?id=1')这个定义为例。

如果当前URL设置为普通模式的话,最后生成的URL地址是: 
http://serverName/index.php?m=Blog&a=read&id=1
如果当前URL设置为PATHINFO模式的话,同样的方法最后生成的URL地址是: 
http://serverName/index.php/Blog/read/id/1
如果当前URL设置为REWRITE模式的话,同样的方法最后生成的URL地址是: 
http://serverName/Blog/read/id/1
如果当前URL设置为REWRITE模式,并且设置了伪静态后缀为.html的话,同样的方法最后生成的URL地址是: 
http://serverName/Blog/read/id/1.html
U方法还可以支持路由,如果我们定义了一个路由规则为:

  1.  'news/:id\d'=>'News/read'

那么可以使用

  1. U('/news/1')

最终生成的URL地址是:

  1. http://serverName/index.php/news/1


注意:如果你是在模板文件中直接使用U方法的话,需要采用 {:U('参数1', '参数2'…)} 的方式,具体参考模板引擎章节的8.3 使用函数内容。

如果你的应用涉及到多个子域名的操作地址,那么也可以在U方法里面指定需要生成地址的域名,例如:

  1. U('Blog/read@blog.thinkphp.cn','id=1');

@后面传入需要指定的域名即可。
此外,U方法的第5个参数如果设置为true,表示自动识别当前的域名,并且会自动根据子域名部署设置APP_SUB_DOMAIN_DEPLOY和APP_SUB_DOMAIN_RULES自动匹配生成当前地址的子域名。
如果开启了URL_CASE_INSENSITIVE,则会统一生成小写的URL地址。

9. URL大小写

只要在项目配置中,增加:

  1. 'URL_CASE_INSENSITIVE' =>true

就可以实现URL访问不再区分大小写了。

这里需要注意一个地方,如果我们定义了一个UserTypeAction的模块类,那么URL的访问应该是:

  1. http://serverName/index.php/user_type/list

  2.  //而不是

  3. http://serverName/index.php/usertype/list

利用系统提供的U方法可以为你自动生成相关的URL地址。
如果设置

  1. 'URL_CASE_INSENSITIVE' =>false

的话,URL就又变成:

  1. http://serverName/index.php/UserType/list

注意:URL不区分大小写并不会改变系统的命名规范,并且只有按照系统的命名规范后才能正确的实现URL不区分大小写。

10. 前置和后置操作

系统会检测当前操作是否具有前置和后置操作,如果存在就会按照顺序执行,前置和后置操作的方法名是在要执行的方法前面加 _before_和_after_,例如:

  1. class CityAction extends Action{
        //前置操作方法
        public function _before_index(){
            echo &#39;before&#39;;
        }
        public function index(){
            echo &#39;index&#39;;
        }
        //后置操作方法
        public function _after_index(){
            echo &#39;after&#39;;
        }
     }

对于任何操作方法我们都可以按照这样的规则来定义前置和后置方法。

<code><code><code><code><code><code><code><code><code>

如果当前的操作并没有定义操作方法,而是直接渲染模板文件,那么如果定义了前置 和后置方法的话,依然会生效。真正有模板输出的可能仅仅是当前的操作,前置和后置操作一般情况是没有任何输出的。
需要注意的是,在有些方法里面使用了exit或者错误输出之类的话 有可能不会再执行后置方法了。
例如,如果在当前操作里面调用了系统Action的error方法,那么将不会再执行后置操作,但是不影响success方法的后置方法执行。

<code><code><code><code><code><code><code><code><code>


11. 跨模块调用

<code>例如,我们在Index模块调用User模块的操作方法

  1. class IndexAction extends Action{
        public function index(){
            //实例化UserAction
            $User = new UserAction();
            //其他用户操作
             //...
            $this->display(); //输出页面模板
        }
     }

因为系统会自动加载Action控制器,因此 我们不需要导入UserAction类就可以直接实例化。
并且为了方便跨模块调用,系统内置了A方法和R方法。    $User = A('User');

<code>事实上,A方法还支持跨分组或者跨项目调用,默认情况下是调用当前项目下面的模块。<br>跨项目调用的格式是:<br>A('[项目名://][分组名/]模块名')<br>例如:

  1. A(&#39;User&#39;) //表示调用当前项目的User模块
    A(&#39;Admin://User&#39;) //表示调用Admin项目的User模块
    A(&#39;Admin/User&#39;) //表示调用Admin分组的User模块
    A(&#39;Admin://Tool/User&#39;) //表示调用Admin项目Tool分组的User模块


R方法表示调用一个模块的某个操作方法,调用格式是:
R('[项目名://][分组名/]模块名/操作名',array('参数1','参数2'…))
例如:

  1. R(&#39;User/info&#39;) //表示调用当前项目的User模块的info操作方法
    R(&#39;Admin/User/info&#39;) //表示调用Admin分组的User模块的info操作方法
    R(&#39;Admin://Tool/User/info&#39;) //表示调用Admin项目Tool分组的User模块的info操作方法

R方法还支持对调用的操作方法需要传入参数,例如User模块中我们定义了一个info方法:

  1. class UserAction extends Action{
        protected function info($id){
            $User = M(&#39;User&#39;);
            $User->find($id);
            //...
        }
     }

接下来,我们可以在其他模块中调用:

  1. R('User/info',array(15))

表示调用当前项目的User模块的info操作方法,并且id参数传入15



12. 页面跳转

<code><code>系统的Action类内置了两个跳转方法success和error,用于页面跳转提示,而且可以支持ajax提交。使用方法很简单,举例如下:

  1. $User = M(&#39;User&#39;); //实例化User对象
    $result = $User->add($data); 
    if($result){
        //设置成功后跳转页面的地址,默认的返回页面是$_SERVER[&#39;HTTP_REFERER&#39;]
        $this->success(&#39;新增成功&#39;, &#39;User/list&#39;);
    } else {
        //错误页面的默认跳转页面是返回前一页,通常不需要设置
        $this->error(&#39;新增失败&#39;);
    }

Success和error方法都有对应的模板,并且是可以设置的,默认的设置是两个方法对应的模板都是:

  1. //默认错误跳转对应的模板文件
    &#39;TMPL_ACTION_ERROR&#39; => THINK_PATH . &#39;Tpl/dispatch_jump.tpl&#39;;
    //默认成功跳转对应的模板文件
    &#39;TMPL_ACTION_SUCCESS&#39; => THINK_PATH . &#39;Tpl/dispatch_jump.tpl&#39;;

也可以使用项目内部的模板文件

  1. //默认错误跳转对应的模板文件
    &#39;TMPL_ACTION_ERROR&#39; => &#39;Public:error&#39;;
    //默认成功跳转对应的模板文件
    &#39;TMPL_ACTION_SUCCESS&#39; => &#39;Public:success&#39;;

模板文件可以使用模板标签,并且可以使用下面的模板变量:

$msgTitle 操作标题
$message 页面提示信息
$status 操作状态 1表示成功 0 表示失败 具体还可以由项目本身定义规则
$waitSecond 跳转等待时间 单位为秒
$jumpUrl 跳转页面地址

success和error方法会自动判断当前请求是否属于Ajax请求,如果属于Ajax请求则会调用ajaxReturn方法返回信息,具体可以参考后面的AJAX返回部分。


3.1版本开始,error和success方法支持传值,无论是跳转模板方式还是ajax方式 都可以使用assign方式传参。例如:

  1. $this->assign(&#39;var1&#39;,&#39;value1&#39;);
    $this->assign(&#39;var2&#39;,&#39;value2&#39;);
    $this->error(&#39;错误的参数&#39;,&#39;要跳转的URL地址&#39;);

当正常方式提交的时候,var1和var2变量会赋值到错误模板的模板变量。
当采用AJAX方式提交的时候,会自动调用ajaxReturn方法传值过去(包括跳转的URL地址url和状态值status)



13. 重定向

Action类的redirect方法可以实现页面的重定向功能。
redirect方法的参数用法和U函数的用法一致(参考上面的URL生成部分),例如:

  1. //重定向到New模块的Category操作
    $this->redirect(&#39;New/category&#39;, array(&#39;cate_id&#39; => 2), 5, &#39;页面跳转中...&#39;);

上面的用法是停留5秒后跳转到News模块的category操作,并且显示页面跳转中字样,重定向后会改变当前的URL地址。
如果你仅仅是想重定向要一个指定的URL地址,而不是到某个模块的操作方法,可以直接使用redirect方法重定向,例如:

  1. //重定向到指定的URL地址

  2. redirect('/New/category/cate_id/2', 5, '页面跳转中...')

Redirect方法的第一个参数是一个URL地址。


14. 获取系统变量

  1. $this->方法名("变量名",["过滤方法"],["默认值"])

<code><code><code>方法名可以支持:

方法名 含义
_get 获取GET参数
_post 获取POST参数
_param 自动判断请求类型获取GET、POST或者PUT参数(3.1新增)
_request 获取REQUEST 参数
_put 获取PUT 参数
_session 获取 $_SESSION 参数


以上就是ThinkPHP- 31的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn