ThinkPHP-3.1, thinkphp-3.1_PHP tutorial

WBOY
Release: 2016-07-13 09:44:23
Original
1313 people have browsed it

ThinkPHP- 3.1, thinkphp-3.1

Basic:

1. Basic concepts

LAMP

LAMP is an open source web 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. use. 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 tripartite confrontation with J2EE and .Net commercial software, and the software development project has a low investment cost in software, so it is favored by the entire IT community. focus on. 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:
Components - data and functions together form a unit 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: ensuring 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 internals 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 sets involve many other different types of components, and the results generated by the referenced component depend 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 application input, processing, and output. 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 uses the corresponding view format. The data returned by the model is transformed and presented to the user through the presentation layer.

ORM

Object/Relation Mapping (ORM for short) came into being 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 public 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 and name it. is "Aspect", that is, aspect. The so-called "aspect", simply put, is to encapsulate the logic or responsibilities that have nothing to do with the business but are jointly called by the business modules, so as to reduce the duplication of code in the system, reduce the coupling between modules, and facilitate future reliability. 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 pieces. Open it to get its internal information. The cut section is the so-called "aspect". Then it restored these cut sections with incredible skill, 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 in the core concern, but are basically 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 combines 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 often the entry file is the first One step is executed.
The advantage of a single entrance is that the overall project is more standardized, because the same entrance often has the same rules for different operations. Another aspect is that the advantage 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 processed 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

目录/文件 说明
ThinkPHP.php 框架入口文件
Common 框架公共文件目录
Conf 框架配置文件目录
Lang 框架系统语言目录
Lib 系统核心基类库目录
Tpl 系统模板目录
Extend 框架扩展目录(关于扩展目录的详细信息请参考后面的扩展章节)
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 (for details about the extension directory, please refer to the extension 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 convention

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 class library files used internally by ThinkPHP, and does not represent externally loaded class library files). They are named using camel case and the first letter is capitalized, such as DbMysql. class.php;
  • Make sure the file names and calls are case-sensitive because Unix-like systems are case-sensitive (ThinkPHP will strictly check case even in debug mode even on Windows platforms);
  • The class name is consistent with the file name (including the upper and lower case mentioned above). 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 classes of different class libraries There are certain standards for naming;
  • Files other than functions, configuration files and other class libraries are generally suffixed with .php (there is no requirement for those imported by third parties);
  • Use lowercase letters and underscores when naming functions, such as get_client_ip;
  • The method is 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;
  • The 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 note that field names do not start 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 capitalized function. This type of function is usually a shortcut definition of certain operations, or has a special effect. 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 Each device has a setting method, and tools can also be used for unified detection and processing), otherwise it may cause many unexpected problems.

4. CBD architecture

ThinkPHP version 3.0 introduces a new CBD (Core Behavior Driver) architecture model, because from the bottom up, the framework adopts a core behavior-driven architecture system. The core retains the most critical parts and sets labels in important locations. Used for tags, other functions are combined using behavioral extensions and drivers. Developers can extend or replace the behavior of a certain tag position according to their own needs, and can easily customize the bottom layer of the framework, or add their own in the application layer. label position and add an apply line. 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 extensions are regarded as a standard mode, then users can customize all these behaviors. 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 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, creation of database and data tables; (optional)
  • Name the project and create the project entry file, and turn on debugging mode;
  • Complete project configuration;
  • Create project function library; (optional)
  • Extensions required for development projects (modes, drivers, tag libraries, 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 check; (optional)
  • Deploy to production environment.

6. Entry file

ThinkPHP adopts a single entrance mode for project deployment and access. No matter what function is completed, a project has a unified (but not necessarily the only) entrance. It should be said that all projects start with an entry file, and the entry files of all projects are similar. The entry file mainly includes:
  • Define framework path, project path and project name (optional)
  • Define related constants for debug mode and run mode (optional)
  • Load the framework entry file (required)

7. Project Directory

The generated project directory structure is similar to the system directory, including:
目录 说明
Common 项目公共文件目录,一般放置项目的公共函数
Conf 项目配置目录,项目所有的配置文件都放在这里
Lang 项目语言包目录(可选 如果不需要多语言支持 可删除)
Lib 项目类库目录,通常包括Action和Model子目录
Tpl 项目模板目录,支持模板主题
Runtime 项目运行时目录,包括Cache(模板缓存)、Temp(数据缓存)、Data(数据目录)和Logs(日志文件)子目录,如果存在分组的话,则首先是分组目录。
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. //Define project name
  2. define('APP_NAME', 'App');
  3. //Define project path
  4. define('APP_PATH', './App/');
  5. //Load the frame into the file
  6. require './App/ThinkPHP/ThinkPHP.php';
APP_NAME refers to the project name. Note that APP_NAME should not be set arbitrarily. It is usually the directory name of the project. If your project is deployed directly under the Web root directory, then you need to set APP_NAME to empty.
APP_PATH refers to the project path (must end with "/"). The project path refers to the location of the project's Common and Lib directories, not the location of the project entry file.
Note: The Runtime directory requires writable permissions in a Unix-like or Linux environment.

8. Deployment directory

目录/文件说明
ThinkPHP 系统目录(下面的目录结构同上面的系统目录)
Public 网站公共资源目录(存放网站的Css、Js和图片等资源)
Uploads 网站上传目录(用户上传的统一目录)
Home 项目目录(下面的目录结构同上面的应用目录)
Admin 后台管理项目目录
…… 更多的项目目录
index.php 项目Home的入口文件
admin.php 项目Admin的入口文件
…… 更多的项目入口文件
The template files of the project are still placed under the Tpl directory of the project, but the externally called resource files, including images, JS and CSS, are placed under the public directory Public of the website and stored in the Images, Js and Css subdirectories, if possible. , you can even place these resource files separately on an external server for remote calling and optimize them.

In fact, the system directory and project directory can be placed under the non-WEB access directory, and only the Public directory and entry files need to be placed under the website directory, thereby improving the security of the website.

If you want to set the directory yourself, you can change the RUNTIME_PATH constant in the entry file, for example:
  1. define('RUNTIME_PATH','./App/temp/');
Note that the RUNTIME_PATH directory must be set with writable permissions.
In addition to customizing the compilation cache directory, it also supports customizing the compilation cache file name, for example:
  1. define('RUNTIME_FILE','./App/temp/runtime_cache.php');
The definition format of all configuration files in the ThinkPHP framework is to return a PHP array, the format is:
  1. //Project configuration file
  2. return array(
  3. 'DEFAULT_MODULE' => 'Index', //Default module
  4. 'URL_MODEL' => '2', //URL mode
  5. 'SESSION_AUTO_START' => true, //Whether to open session
  6. //More configuration parameters
  7. //...
  8. );
Configuration parameters are not case-sensitive (because no matter whether uppercase or lowercase definitions are defined, they will be converted to lowercase)
You can also use a two-dimensional array in the configuration file to configure more information, for example:
  1. //Project configuration file
  2. return array(
  3. 'DEFAULT_MODULE' => 'Index', //Default module
  4. 'URL_MODEL' => '2', //URL mode
  5. 'SESSION_AUTO_START' => true, //Whether to open session
  6. 'USER_CONFIG' => array(
  7. 'USER_AUTH' => true,
  8. 'USER_TYPE' => 2,
  9. ),
  10. //More configuration parameters
  11. //...
  12. );
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, project configuration, debugging configuration

Convention over 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), which configures common parameters by default according to most uses. 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 debug state, which means the default configuration parameters are:
  1. 'APP_STATUS' => 'debug', //Application debug mode status
The debug.php configuration file only needs to configure different parameters or new parameters from the project configuration file and system debugging configuration file.
If you want to add application status in debug mode, such as test status, you can change the settings in the project configuration file as follows:
  1. 'APP_STATUS' => 'test', //Application debug mode status
Since the debug mode does not have any cache, it involves more file IO operations and template real-time compilation. Therefore, when the debug mode is turned on, the performance will decrease to a certain extent, but it will not affect the performance of the deployment mode.
Note: Once debugging mode is turned off, the project’s debugging configuration file becomes invalid immediately.

10. Group configuration and read configuration, dynamic configuration

If module grouping is enabled, you can define a configuration file for each group separately. The grouping configuration file is located at:
Project Configuration Directory/Group Name/config.php
You can enable grouping through the following configuration:
  1. 'APP_GROUP_LIST' => 'Home,Admin', //Project group setting
  2. 'DEFAULT_GROUP' => 'Home', //Default group
Now that two groups, Home and Admin, are defined, we can define the group configuration file as follows:
Conf/Home/config.php
Conf/Admin/config.php
Configuration of each group The file is only valid in the current group. The definition format of the group configuration is the same as the project configuration.
Note: The group name is 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. The C method can also be used to read two-dimensional configuration:
  1. C('USER_CONFIG.USER_TYPE')//Get the user type settings in user configuration
Because the configuration parameters are globally valid, 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.
Set 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');
It 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 new value:
  1. C('USER_CONFIG.USER_TYPE','1');
Starting from version 3.1, the C function supports the configuration saving function, which is only valid for batch settings. How to use:
  1. C($array,'name');
where array is an array variable, which will save the batch-set configuration parameter list to the cache data identified by name

To obtain the cached setting list data, you can use
  1. C('','name'); //or C(null,'name');
The cached configuration data identified by name will be read into the 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 before it can 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 extension configuration is as follows (multiple files separated by commas):
  1. 'LOAD_EXT_CONFIG' => 'user,db', // Load extended configuration file
The project is set to load extension configuration files user.php and db.php 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 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 approach can avoid parameter conflict problems in large project situations. Some of the following configuration files are already used by the system, please do not redefine them as custom extended configurations:
文件名 说明
config.php 项目配置文件
tags.php 项目行为配置文件
alias.php 项目别名定义文件
debug.php 项目调试模式配置文件(以及项目设置的APP_STATUS对应的配置文件)
core.php 项目追加的核心编译列表文件(不会覆盖核心编译列表)

12. Function library

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

System function library

The library 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 is a public function library in the framework standard mode Function library, other modes can replace loading your own public function library or redefine the functions in the public function library;
runtime.php is the framework runtime file, which will only be loaded in debugging mode or compilation process, so The methods cannot be called directly in the project;

Project function library

Library project function library is usually located under the Common directory of the project. The file name is common.php. This file will be automatically loaded during execution and merged into the project compilation unified cache. If the group deployment method is used, and there is " "Group name/function.php" file will also be automatically loaded according to the execution of the current group, so all functions in the project function library can 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

Functions in the system function library and project function library can be called directly without loading. For the project's extended function library, you can call it in the following two ways:
Dynamic loading
We can define LOAD_EXT_FILE in the project configuration file Parameters, for example:
  1. "LOAD_EXT_FILE"=>"user,db"
Through the above settings, the extended function library files user.php and db.php under the public directory of the project will be automatically loaded during execution, so that the extended function library user.php and db can be called directly in the project. functions in php, and the function modifications of the extended function library take effect in real time.

Manual loading
If your function is only occasionally used 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, as follows:
  1. load("@.user")
@.user means loading the user function file of the current project, so that you can directly extend the functions in the user.php function library.

13. Class Library

ThinkPHP's class library includes a base class library and an application class library. The system's class library naming rules are as follows:
类库 规则 示例
控制器类 模块名 Action 例如 UserAction、InfoAction
模型类 模型名 Model 例如 UserModel、InfoModel
行为类 行为名 Behavior 例如CheckRouteBehavior
Widget类 Widget名 Widget 例如BlogInfoWidget
驱动类 引擎名 驱动名 例如DbMysql表示mysql数据库驱动、CacheFile表示文件缓存驱动

Base class library

The 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:
目录 调用路径 说明
Lib/Core Think.Core 核心类库包
Lib/Behavior Think.Behavior 内置行为类库包
Lib/Driver Think.Driver 内置驱动类库包
Lib/Template Think.Template 内置模板引擎类库包
The core class library package contains the following core class libraries:
类名 说明
Action 系统基础控制器类
App 系统应用类
Behavior 系统行为基础类
Cache 系统缓存类
Db 系统抽象数据库类
Dispatcher URL调度类
Log 系统日志类
Model 系统基础模型类
Think 系统入口和静态类
ThinkException 系统基础异常类
View 视图类
Widget 系统Widget基础类

Application library

Application class libraries refer to class libraries that are 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:
目录 调用路径 说明
Lib/Action @.Action或自动加载 控制器类库包
Lib/Model @.Model或自动加载 模型类库包
Lib/Behavior 用B方法调用或自动加载 应用行为类库包
Lib/Widget 用W方法在模板中调用 应用Widget类库包
The project can add its own class library package under the project class library directory according to its own needs, such as Lib/Common, Lib/Tool, etc.

Class library import

1. Import explicit import

ThinkPHP simulates Java's class library import mechanism and uniformly uses the import method to load class files. The import method is ThinkPHP's built-in class library import method, which provides a convenient and flexible file import mechanism and can completely replace PHP's require and include methods. For example:
  1. import("Think.Util.Session");
  2. import("App.Model.UserModel");
The import method has a caching and detection mechanism. The same file will not be imported repeatedly. If a class library file with the same name in a different location is imported, the system will not import it again. Note: There is a case difference under Unix or Linux hosts, so when using the import method, pay attention to the case of the directory name and class library name, otherwise the import will fail. For the import method, the system will automatically identify the location of the imported class library file. The convention of ThinkPHP is that the import of Think, ORG, and Com packages is imported as the base class library, otherwise it is considered to be the import of the project application class library.
  1. import("Think.Util.Session");
  2. import("ORG.Util.Page");
The above two methods import the Util/Session.class.php file of Think base class library and the Util/Page.class.php file of ORG extended class library package respectively.
It is also very simple to import the application class library file of the project. Just use the following method, which looks similar to the method of importing the base class library:
  1. import("MyApp.Action.UserAction");
  2. import("MyApp.Model.InfoModel");
The above methods respectively represent importing the Lib/Action/UserAction.class.php and Lib/Model/InfoModel.class.php class files under the MyApp project. Usually we import the required class library files into the current project, so we can use the following method to simplify the code
  1. import("@.Action.UserAction");
  2. import("@.Model.InfoModel");

2. Import alias

In addition to the namespace import method, the import method can also support alias import. To use alias import, you must first define the alias. We can add alias.php under the project configuration directory to define the class library alias that needs to be used in the project. For example:
  1. return array(
  2. 'rbac' =>LIB_PATH.'Common/Rbac.class.php',
  3. 'page' =>LIB_PATH.'Common/Page.class.php',
  4. );
Then, you can use it directly now:
  1. import("rbac");
  2. import("page");
Import Rbac and Page classes. The alias import method prohibits the use of the second and third parameters of the import method. The alias import method is more efficient than the namespace import method. The disadvantage is that the relevant aliases need to be defined in advance.

Import third-party libraries

Third-party class libraries are uniformly placed in the Vendor directory under the system extension directory, and are imported using the vendor method. The parameters are the same as the import method, except that the default values ​​have changed. For example, we put Zend's FilterDir.php under the Vendor directory. At this time, the path of the Dir file is VendorZendFilterDir.php, we use the vendor method to import and just use:
  1. Vendor('Zend.Filter.Dir');
You can import the Dir class library.
The Vendor method can also support the same basic path and file name suffix parameters as the import method, for example:
  1. Vendor('Zend.Filter.Dir',dirname(__FILE__),'.class.php');

Auto loading

In most cases, we do not need to manually import class libraries, but can use the automatic loading mechanism through configuration. The automatic loading mechanism is truly on-demand loading, which can greatly improve performance. There are three situations of automatic loading. According to the loading priority, they are: automatic loading of aliases, automatic loading of system rules and automatic loading of custom paths.

1. Automatic loading of aliases

We mentioned how to define aliases earlier, and used the import method to import aliases. In fact, all class libraries that define aliases do not need to be loaded manually, the system will automatically load them on demand.

2. Automatic loading of system rules

If you do not define an alias, the system will first judge the loading according to the built-in rules. The system rules are only for behavior classes, model classes and controller classes. The search rules are as follows:
类名 规则 说明
行为类 规则1 搜索系统类库目录下面的Behavior目录
规则2 搜索系统扩展目录下面的Behavior目录
规则3 搜索应用类库目录下面的Behavior目录
规则4 如果启用了模式扩展,则搜索模式扩展目录下面的Behavior目录
模型类 规则1 如果启用分组,则搜索应用类库目录的Model/当前分组 目录
规则2 搜索应用类库下面的Model目录
规则3 搜索系统扩展目录下面的Model目录
控制器类 规则1 如果启用分组,则搜索应用类库目录的Action/当前分组 目录
规则2 搜索项目类库目录下面的Action目录
规则3 搜索系统扩展目录下面的Action目录
Note: The search priority is from top to bottom. Once found, it will be returned and subsequent rules will no longer detect it. If the class library is still not found after all rule detection is completed, the third custom path automatic loading detection will be started.

3. Automatic loading of custom paths

When your class libraries are concentrated in a certain directory and you don’t want to define too many alias imports, you can use the custom path automatic loading method. This method requires adding the automatically loaded search path in the project configuration file, for example:
  1. 'APP_AUTOLOAD_PATH' =>'@.Common,@.Tool',
means that the class libraries under the Common and Tool directories under the current project class library directory can be automatically loaded. Separate multiple search paths with commas, and pay attention to the order of definition, which is the order of automatic search.
Note: The automatic search path definition can only use the namespace method, which means that this method can only automatically load the class library files under the project class library directory and the base class library directory. -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------

Controller:

1. URL pattern

Traditional file entry access will be uniformly parsed and scheduled by URL parameters. ThinkPHP supports four URL modes, which can be defined by setting the URL_MODEL parameter, including normal mode, PATHINFO, REWRITE and compatibility mode. 1. Normal mode: Set URL_MODEL to 0
Adopt traditional URL parameter mode
  1. http://serverName/appName/?m=module&a=action&id=1
2. PATHINFO mode (default mode) : Set URL_MODEL to 1
PATHINFO mode is used by default. ThinkPHP has built-in powerful PATHINFO support, providing flexible and friendly URL support. . PATHINFO mode automatically identifies modules and operations, such as
  1. http://serverName/appName/module/action/id/1/or
  1. http://serverName/appName/module,action,id,1/
3. REWRITE mode: Set URL_MODEL to 2
This URL mode has the same function as the PATHINFO mode, except that you do not need to write an entry file in the URL, and you can define a .htaccess file. After turning on Apache's URL_REWRITE module, you can enable REWRITE mode. For details, refer to the URL rewriting section below. 4. Compatibility mode : Set URL_MODEL to 3
Compatibility mode is a combination of normal mode and PATHINFO mode, and allows applications to directly switch to PATHINFO mode when needed without changing templates and programs. Can also be integrated with URL_WRITE mode. Compatibility mode URLs can support any operating environment. The effect of compatibility mode is:
  1. http://serverName/appName/?s=/module/action/id/1/
And it can also support the definition of parameter delimiter symbols. For example, when URL_PATHINFO_DEPR is ~, the following URL is valid:
  1. http://serverName/appName/?s=module~action~id~1
In fact, the VAR_PATHINFO parameter is used to simulate the PATHINFO mode with the implementation of normal mode. However, in compatibility mode, you do not need to pass the s variable yourself, but the system automatically completes the URL part. Because of this feature, compatibility mode can be switched directly between compatibility mode and PATHINFO mode without changing the URL address connection in the template file. Our recommended method is to use PATHINFO mode for development. If the environment does not support PATHINFO during deployment, it can be deployed in compatible URL mode. No changes are required in the program and template.

2. Modules and operations

http://domain name/project name/group name/module name/operation name/other parameters
Dispatcher will obtain the currently required project, group (if defined) module, operation and Other parameters, in some cases, the project name may not appear in the URL address (usually the entry file represents a certain project, and the entry file can be hidden).
Each module is a controller class, usually located under the LibAction directory of the project.
Starting from version 3.1, the ACTION_SUFFIX configuration parameter is added to set the suffix of the operation method.
For example, if setting:
  1. 'ACTION_SUFFIX'=>'Act'
Then the add operation to access a module corresponds to the operation method of reading the module class, which is changed from the original add method to the addAct method.

3. Define controllers and empty operations, empty modules

If an application does not need to interact with the database, it does not need to define a model class, but it must define an Action controller, which is usually located under the Lib/Action directory of the project.
The definition of Action controller is very simple, just inherit the Action base class, for example:
  1. Class UserAction extends Action{}
The name of the controller file is 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:
配置参数 说明
APP_GROUP_LIST 项目分组列表(配置即表示开启分组)
DEFAULT_GROUP 默认分组(默认值为Home)
TMPL_FILE_DEPR 分组模板下面模块和操作的分隔符,默认值为“/”
VAR_GROUP 分组的URL参数名,默认为g(普通模式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 group is allowed to be set by default.

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, 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 the URL characteristics of a static page, but has the same execution effect as the previous URL and will not affect the use of the 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 to generate the URL in the template file. 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, just 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 | 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, see: http://doc.thinkphp.cn/manual/url_route.html

7. URL Rewriting

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

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

8. URL generation

<code><code><code><code><code><code><code><code><code><code><code><code>In order to match the URL pattern used, we need to be able 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. <code><code><code><code><code><code><code><code><code><code><code><code>为了配合所使用的URL模式,我们需要能够动态的根据当前的URL设置生成对应的URL地址,为此,ThinkPHP内置提供了U方法,用于URL的动态生成,可以确保项目在移植过程中不受环境的影响。
U方法的定义规则如下(方括号内参数根据实际应用决定):<code>The definition rules of U method are as follows (the parameters in square brackets are determined according to the actual application): <code>
  1. U('[Group/Module/Operation]?Parameter' [,'Parameter','Pseudo-static suffix','Whether to jump','Display domain name'])
<code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code>If not When defining projects and modules, they represent the current project and module names. Here are some simple examples: <code>
  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 URL address of the select operation of the User module of the Admin group
<code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code>U method The second parameter supports two definition methods: array and string. If it is only a string parameter, it can be defined in the first parameter, for example: <code>
  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><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code>
Three types The methods are equivalent. They generate the cate operation of the Blog module and the cate_id is 1 and the status is 1 URL address <code>. However, the following definition method is not allowed to pass parameters <code>
  1. U('Blog/cate/cate_id/1/status/1')
<code><code><code><code><code><code><code><code><code><code><code><code>
    According to different URL settings of the project, the same U method call can intelligently produce different URL address effects, such as for
  1. U ('Blog/read?id=1') is an example.

If the current URL is set to normal mode, the last generated URL address is:
http://serverName/index.php?m=Blog&a=read&id=1
If the current URL is set to PATHINFO mode , the URL address finally generated by the same method is:
http://serverName/index.php/Blog/read/id/1
If the current URL is set to REWRITE mode, the URL finally generated by the same method The address is:
http://serverName/Blog/read/id/1
If the current URL is set to REWRITE mode and the pseudo-static suffix is ​​set to .html, the URL address finally generated by the same method is :
http://serverName/Blog/read/id/1.html
    U method can also support routing, if we define a routing rule as:
  1. 'news/:idd'=>'News/read'
    Then you can use it
  1. U('/news/1')
    The final generated URL address is:
  1. http://serverName/index.php/news/1

Note: If you use the U method directly in the template file, you need to use {:U('Parameter 1', 'Parameter 2'...)}. For details, refer to 8.3 Using Functions in the Template Engine Chapter.

<code>If your application involves the operation addresses of multiple subdomains, you can also specify the domain name that needs to generate the address in the U method, for example: <code>

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

Just pass in the domain name that needs to be specified after <code><code><br>@. <br><br>In addition, if the fifth parameter of the U method is set to true, it means that the current domain name is automatically recognized, and APP_SUB_DOMAIN_DEPLOY and APP_SUB_DOMAIN_RULES are automatically matched to generate the subdomain name of the current address based on the subdomain deployment settings.

If URL_CASE_INSENSITIVE is turned on, lowercase URL addresses will be generated uniformly.

9. URL case<code> Just add: <code><p> in the project configuration </p> <ol data-front-font-size="18px"> <li> </li>'URL_CASE_INSENSITIVE' =>true</ol> <p> <code><code>

can realize that URL access is no longer case-sensitive.

One thing to note here is that if we define a module class of UserTypeAction, then the URL access should be: <code>

  1. http://serverName/index.php/user_type/list
  2. // instead of
  3. http://serverName/index.php/usertype/list

<code>Use the U method provided by the system to automatically generate relevant URL addresses for you.
If set<code>

  1. 'URL_CASE_INSENSITIVE' =>false

<code>, the URL will become: <code>

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

<code>Note: URL case insensitivity does not change the system naming convention, and only by following the system naming convention can URL case insensitivity be correctly implemented.

10. Pre- and post-operations

The system will detect whether the current operation has pre- and post-operations. If they exist, they will be executed in order. The method names of pre- and post-operations are to add _before_ and _after_ in front of the method to be executed, for example: <code>

  1. class CityAction extends Action{
  2. //Pre-operation method
  3. public function _before_index(){
  4. echo 'before
    ';
  5. }
  6. public function index(){
  7. echo 'index
    ';
  8. }
  9. //Post-operation method
  10. public function _after_index(){
  11. echo 'after
    ';
  12. }
  13. }
For any operation method, we can define pre- and post-methods according to such rules.
<code><code><code><code><code><code><code><code><code><code><code><code> If the current operation does not define an operation method, but directly renders the template file, then if the pre- and post-methods are defined, they will still take effect. The real template output may only be the current operation, and the pre- and post-operations generally do not have any output.
It should be noted that if exit or error output is used in some methods, the post-method may no longer be executed.
For example, if the error method of the system Action is called in the current operation, the post-operation will not be executed, but the post-method execution of the success method will not be affected.
<code><code><code><code><code><code><code><code><code><code><code><code> <code><code><code><code>

11. Cross-module calling

<code><code><code><code>例如,我们在Index模块调用User模块的操作方法<code>For example, we call the operation method of the User module in the Index module <code>
  1. class IndexAction extends Action{
  2. public function index(){
  3. //Instantiate UserAction
  4. $User = new UserAction();
  5. //Other user operations
  6.           //...
  7. $this->display(); //Output page template
  8. }
  9. }
<code><code><code><code>
Because the system will automatically load the Action controller, we can instantiate it directly without importing the UserAction class. And in order to facilitate cross-module calling, the system has built-in A method and R method. $User = A('User');
<code> <code><code><code>事实上,A方法还支持跨分组或者跨项目调用,默认情况下是调用当前项目下面的模块。
跨项目调用的格式是:
A('[项目名://][分组名/]模块名')
例如:<code> <code><code>
In fact, method A also supports cross-group or cross-project calls. By default, the module under the current project is called. The format of cross-project calls is:
    A('[project name://][group name/]module name')
  1. For example: <code><li> <li> <li> </li>A('User') //Indicates calling the User module of the current project
<code><code>A('Admin://User') //Indicates calling the User module of the Admin project
A('Admin/User') //Indicates calling the User module of the Admin group A('Admin://Tool/User') //Represents the User module that calls the Admin project Tool group
<code><code> The R method represents calling an operation method of a module. The calling format is: R('[Project name://][Group name/]Module name/Operation name',array('Parameter 1' ,'Parameter 2'...))For example:
  1. R('User/info') //Indicates calling the info operation method of the User module of the current project
  2. R('Admin/User/info') //Indicates calling the info operation method of the User module of the Admin group
  3. R('Admin://Tool/User/info') //Indicates calling the info operation method of the User module of the Admin project Tool group
The R method also supports the need to pass in parameters for the called operation method. For example, in the User module we define an info method:
  1. class UserAction extends Action{
  2. protected function info($id){
  3. $User = M('User');
  4. $User->find($id);
  5.           //...
  6. }
  7. }
Next, we can call in other modules:
  1. R('User/info',array(15))
indicates that the info operation method of the User module of the current project is called, and the id parameter is passed in 15 <code> <code><code><code><code><code>

12. Page jump

<code><code><code>The system's Action class has two built-in jump methods, success and error, which are used for page jump prompts and can support ajax submission. The method of use is very simple, for example: <code><code><code>系统的Action类内置了两个跳转方法success和error,用于页面跳转提示,而且可以支持ajax提交。使用方法很简单,举例如下:<code>
  1. $User = M('User'); //Instantiate User object
  2. $result = $User->add($data);
  3. if($result){
  4. //The address of the jump page after successful setting. The default return page is $_SERVER['HTTP_REFERER']
  5. $this->success('Add successfully', 'User/list');
  6. } else {
  7. //The default jump page of the error page is to return to the previous page, usually there is no need to set it
  8. $this->error('Add failed');
  9. }
<code><code><code><code><code> Success and error methods have corresponding templates and can be set. The default setting is that the templates corresponding to both methods are:
  1. //The template file corresponding to the default error jump
  2. 'TMPL_ACTION_ERROR' => THINK_PATH . 'Tpl/dispatch_jump.tpl';
  3. //The corresponding template file will be successfully jumped by default
  4. 'TMPL_ACTION_SUCCESS' => THINK_PATH . 'Tpl/dispatch_jump.tpl';
You can also use template files within the project
  1. //The template file corresponding to the default error jump
  2. 'TMPL_ACTION_ERROR' => 'Public:error';
  3. //The corresponding template file will be successfully jumped by default
  4. 'TMPL_ACTION_SUCCESS' => 'Public:success';
Template files can use template tags and can use the following template variables:
$msgTitle 操作标题
$message 页面提示信息
$status 操作状态 1表示成功 0 表示失败 具体还可以由项目本身定义规则
$waitSecond 跳转等待时间 单位为秒
$jumpUrl 跳转页面地址
The success and error methods will automatically determine whether the current request is an Ajax request. If it is an Ajax request, the ajaxReturn method will be called to return information. For details, please refer to the AJAX return section later. <code><code><code> Starting from version 3.1, the error and success methods support value passing. Whether it is the jump template method or the ajax method, you can use the assign method to pass parameters. For example:
  1. $this->assign('var1','value1');
  2. $this->assign('var2','value2');
  3. $this->error('wrong parameters','URL address to jump');
When submitted in the normal way, the var1 and var2 variables will be assigned to the template variables of the error template.
When submitting using AJAX, the ajaxReturn method will be automatically called to pass the value (including the jump URL address url and status value status) <code><code><code>

13. Redirect

The redirect method of the Action class can implement the page redirection function.
The parameter usage of the redirect method is consistent with the usage of the U function (refer to the URL generation part above), for example:
  1. //Redirect to the Category operation of the New module
  2. $this->redirect('New/category', array('cate_id' => 2), 5, 'Page jumping...');
The above usage is to jump to the category operation of the News module after staying for 5 seconds, and display the words page jumping. After redirection, the current URL address will be changed.
If you just want to redirect to a specified URL address, rather than to the operation method of a certain module, you can directly use the redirect method to redirect, for example:
  1. //Redirect to the specified URL address
  2. redirect('/N
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template