Instantiate the UserEvent controller (the corresponding file is located in Lib/Event/UserEvent.class.).
After instantiating a controller, you can call methods in the controller. However, it should be noted that when calling across projects, if your operation method has special variable operations for the current controller, there will be some unknowns. Therefore, generally speaking, officials recommend that the controller layer that requires public calls be developed separately without too many dependencies.
This is a new function that comes into being with the behavior and can perform a certain behavior, such as
That is, before the project starts, all functions defined by this behavior are executed. Supports 2 parameters, the second parameter needs to accept an array, for example
Method C is the method used by Think to set, obtain, and save configuration parameters, and is used more frequently.
To understand the C method, you need to first understand the configuration of Think, because all operations of the C method are related to the configuration. Think's configuration file is defined in array format.
Due to the function overloading design, there are many usages. Let’s explain them one by one.
Set parameters
Indicates that the value of the DB_NAME configuration parameter is set to think. Since the configuration parameters are not case-sensitive, the following writing method is the same:
However, it is recommended to keep the configuration definition specifications in uniform capital letters.
All parameters of the project can be dynamically changed through this method before taking effect. The last set value will overwrite the previous settings or definitions in the conventional configuration. You can also use the parameter configuration method to add new configurations.
It is not recommended to configure parameters beyond level two.
If you want to set multiple parameters, you can use batch settings, for example:
If the first parameter of the C method is passed into an array, it means batch assignment. The above assignment is equivalent to:
If the USER_ID parameter has not been defined, NULL is returned.
If the incoming configuration parameters are empty, it means obtaining all parameters:
Version .1 adds a function to permanently save setting parameters, which is only for batch assignment, for example:
After setting the config parameters in batches, all current configuration parameters will be saved to the cache file (or other configured caching methods).
$config = C('','name');
Among them, name is the cache identifier used when saving parameters earlier. It must be consistent to correctly retrieve the saved parameters. The retrieved parameters will be merged with the current configuration parameters, without manual merging.
D method
The D method should be the most commonly used method. It is used to instantiate custom model classes. It is an encapsulation of the Model class instantiation by the Think framework, and implements the singleton mode, supporting cross-project and group calls. , the calling format is as follows:
D('[project://][group/]model','model layer name')
The return value of the method is the instantiated model object.
The D method can automatically detect the model class. If a custom model class exists, the custom model class will be instantiated. If it does not exist, the Model base class will be instantiated. At the same time, the instantiated model will not be instantiated repeatedly. change.
The most common use of the D method is to instantiate a custom model of the current project, for example:
// Instantiate the User model
$User = D('User');
Will import the Lib/Model/UserModel.class. file under the current project, and then instantiate the UserModel class, so the actual code may be equivalent to the following:
import(
'@.Model.UserModel');
$User = new UserModel();
But if you use the D method, if the UserModel class does not exist, it will be called automatically
new Model('User');
And there is no need to instantiate again when called for the second time, which can reduce a certain amount of object instantiation overhead.
The D method can support instantiating models across groups and projects, for example:
//Instantiate the User model of the Admin project
D('Admin://User')
//Instantiate the User model of the Admin group
D('Admin/User')
Note: To implement the cross-project calling model, you must ensure that the directory structures of the two projects are parallel.
Starting from version .1, due to the added support for hierarchical models, the D method can also instantiate other models, such as:
// Instantiate the UserService class
$User = D('User','Service');
// Instantiate the UserLogic class
$User = D('User','Logic');
D('User','Service');
Lib/Service/UserService.class. will be imported and instantiated, which is equivalent to the following code:
import(
'@.Service.UserService');
$User = new UserSerivce();
F method
The F method is actually a subset of the S method. It is only used for simple data caching and can only support file formats. It does not support cache validity periods. Because it uses the return method, its efficiency is higher than the S method. Therefore we also call it the fast cache method.
The characteristics of the F method are:
Simple data caching;
Save as file;
Load the cache by returning data;
Supports subdirectory caching and automatic creation;
Supports cache deletion and batch deletion;
Write and read cache
F('data','test data');
div>
The default saving starting path is DATA_PATH (this constant is located under RUNTIME_PATH.'Data/' in the default configuration), which means that a cache file with the file name DATA_PATH.'data.' will be generated.
Note: Make sure your cache identifier is unique to avoid data overwrites and conflicts.
The next time you read cached data, use:
$Data = F('data');
We can save it in a subdirectory, for example:
F('user/data',$data); // Caching writes
F('user/data'); // Read cache
The DATA_PATH.'user/data.' cache file will be generated. If the user subdirectory does not exist, it will be automatically created. Multi-level subdirectories can also be supported, for example:
F('level1/level2/data',$data);
If you need to specify the starting directory of the cache, you can use the following method:
F('data',$data,TEMP_PATH);
div>
When obtaining, you need to use:
F('data','',TEMP_PATH);
div>
Delete cache
Deleting the cache is also very simple, use:
F('data',NULL);
Passing in NULL as the second parameter means deleting the data cache identified as data.
Supports batch deletion function, especially for subdirectory cache. Suppose we want to delete all cached data under the user subdirectory, we can use:
F('user/*',NULL);
Or use filter conditions to delete, for example:
F('user/[^a]*',NULL) ;
G method
The functions that Thinkphp has long required to be completed through the debug_start, debug_end methods and even the Debug class have been replaced by a simple G method in version 3.1, which is a gorgeous upgrade.
The function of G method includes two functions: marking position and interval statistics. Let’s take a look at the specific usage:
Mark location
The first usage of G method is to mark the position, for example:
G('begin');
Indicates that the current position is marked as the begin tag, and the execution time of the current position is recorded. If the environment supports it, the memory usage can also be recorded. G method markers can be called anywhere.
Run time statistics
After marking the position, we can call the G method again to perform interval statistics, for example:
G('begin');
// ...Other snippets
G('end');
// ...maybe there is other code here
// Carry out statistical interval
echo G('begin','end').'s';
G('begin','end') means counting the execution time from the begin position to the end position (unit is seconds). Begin must be a marked position. If the end position has not been marked at this time, it will automatically Mark the current position as the end tag, and the output result is similar to:
0.0056s
The default statistical accuracy is 4 decimal places. If you feel that this statistical accuracy is not enough, you can also set it as follows:
G('begin','end',6).' s';
Possible output would become:
0.005587s
Memory overhead statistics
If your environment supports memory usage statistics, you can also use the G method to perform interval memory overhead statistics (unit: kb), for example:
echo G('begin','end','m' ).'kb';
The third parameter uses m to indicate memory overhead statistics. The output result may be:
625kb
Similarly, if the end tag is not marked, the current position will be automatically marked as the end tag first.
If the environment does not support memory statistics, this parameter is invalid and interval running time statistics will still be performed.
Forget debug_start and debug_end, simplicity is the way to go, you know~
I method
Thinkphp's I method is new in version 3.1.3. If you are using the previous 3.* version, you can directly refer to the variables part of the 3.1 quick start tutorial series.
Overview
As you can see, the I method is a new member of Thinkphp's many single-letter functions. Its name comes from the English Input (input). It is mainly used to obtain system input variables more conveniently and safely. It can be used anywhere. The usage format is as follows:
I('Variable type.Variable name',['Default value'],['Filter method'])
Variable type refers to the request method or input type, including:
get Get GET parameters
post Get POST parameters
param automatically determines the request type to obtain GET, POST or PUT parameters
request gets REQUEST parameters
put gets PUT parameters
session gets the $_SESSION parameter
cookie gets $_COOKIE parameter
server gets the $_SERVER parameter
globals gets $GLOBALS parameters
Note: Variable types are not case-sensitive.
Variable names are strictly case-sensitive.
Both the default value and the filtering method are optional parameters.
Usage
Let's take the GET variable type as an example to illustrate the use of the I method:
echo I('get.id'); // Equivalent to $_GET['id']
echo I('get.name'); // Equivalent to $_GET['name']
Support default value:
echo I('get.id',0); // If $_GET['id'] does not exist, return 0
echo I('get.name',''); // If $_GET['name'] does not exist, return an empty string
Filter using method:
echo I('get.name','','htmlspecialchars '); // Use the htmlspecialchars method to filter $_GET['name'], and return an empty string if it does not exist
Supports directly obtaining the entire variable type, for example:
I('get.'); // Get the entire $_GET array
In the same way, we can get variables of post or other input types, for example:
1.I('post.name','',' htmlspecialchars'); // Use the htmlspecialchars method to filter $_POST['name'], and return an empty string if it does not exist
I('session.user_id',0); // Get $_SESSION['user_id'] If it does not exist, it defaults to 0
I('cookie.'); // Get the entire $_COOKIE array
I('server.REQUEST_METHOD'); // Get $_SERVER['REQUEST_METHOD']
The param variable type is a framework-specific method of obtaining variables that supports automatic determination of the current request type, for example:
echo I('param.id');
If the current request type is GET, it is equivalent to GET['id']. If the current request type is POST or PUT, it is equivalent to getting _POST['id'] or PUT parameter id.
And param type variables can also use digital index to obtain URL parameters (the PATHINFO mode parameter must be valid, whether it is GET or POST), for example:
The current access URL address is
http://serverName/index./New/2013/06 /01
Then we can pass
echo I('param.1'); // Output 2013
echo I('param.2'); // Output 06
echo I('param.3'); // Output 01
In fact, the writing method of param variable type can be simplified to:
I('id'); // Equivalent to I(' param.id')
I('name'); // Equivalent to I('param.name')
Variable filter
When using the I method, the variables actually go through two filters. The first is global filtering. Global filtering is done by configuring the VAR_FILTERS parameter. It must be noted here that after version 3.1, the filtering mechanism of the VAR_FILTERS parameter has been changed to recursive filtering using the array_walk_recursive method. , the main requirement for the filtering method is that it must be returned by reference, so setting htmlspecialchars here is invalid. You can customize a method, for example:
function filter_default(&$value){
$value = htmlspecialchars($value);
}
Then configure:
'VAR_FILTERS'=>'filter_default'
If you need to filter multiple times, you can use:
'VAR_FILTERS'=>'filter_default,filter_exp'
The filter_exp method is a security filtering method built into the framework, which is used to prevent injection attacks using the EXP function of the model.
Because the VAR_FILTERS parameter sets a global filtering mechanism and uses recursive filtering, which has an impact on efficiency, we recommend directly filtering the obtained variables. In addition to setting the filtering method in the third parameter of the I method, Filtering can also be set by configuring the DEFAULT_FILTER parameter. In fact, the default setting of this parameter is:
'DEFAULT_FILTER' => 'htmlspecialchars'
In other words, all acquisition variables of the I method will be filtered by htmlspecialchars, then:
I('get.name'); // Equivalent to htmlspecialchars ($_GET['name'])
Similarly, this parameter can also support multiple filters, for example:
'DEFAULT_FILTER' => 'strip_tags,htmlspecialchars'
I('get.name'); // Equivalent to htmlspecialchars (strip_tags($_GET['name']))
If we specify the filtering method when using the I method, the DEFAULT_FILTER setting will be ignored, for example:
echo I('get.name','','strip_tags '); // Equivalent to strip_tags($_GET['name'])
If the third parameter of the I method is passed in the function name, it means that the function is called to filter the variable and returns it (if the variable is an array, array_map is automatically used for filtering), otherwise the built-in filter_var method is called for filtering. , for example:
I('post.email','',FILTER_VALIDATE_EMAIL);
Indicates that $_POST['email'] will be format verified, and if it does not meet the requirements, an empty string will be returned.
(For more verification formats, please refer to the official manual for filter_var usage.)
Or you can use the following character identification:
I('post.email','','email');
The supported filter names must be valid values in the filter_list method (different server environments may differ). Possible supported filter names include:
int
boolean
float
validate_regexp
validate_url
validate_email
validate_ip
string
stripped
encoded
special_chars
unsafe_raw
email
url
number_int
number_float
magic_quotes
callback
In some special cases, we do not want to perform any filtering, even if DEFAULT_FILTER has been set, you can use:
I('get.name','',NULL);
Once the filtering parameter is set to NULL, it means that no filtering will be performed anymore.
L method
The L method is used to set and get the current language definition when multiple languages are enabled.
Calling format: L('Language variable',['Language value'])
Set language variables
In addition to using language packages to define language variables, we can use the L method to dynamically set language variables, for example:
L('LANG_VAR','Language definition');
div>
Language definitions are not case-sensitive, so the following are also equivalent:
L('lang_var','language definition');
div>
However, for the sake of standardization, we recommend that you use uppercase letters to define language variables.
The L method supports batch setting of language variables, for example:
$lang['lang_var1'] = 'Language definition 1';
$lang['lang_var2'] = 'Language definition 2';
$lang['lang_var3'] = 'Language definition 3';
L($lang);
Indicates that three language variables lang_var1, lang_var2 and lang_var3 are set at the same time.
[-more-]
Get language variables
$langVar = L('LANG_VAR');
Or:
$langVar = L('lang_var');
If the parameter is empty, it means to obtain all currently defined language variables (including those in the language definition file):
$lang = L();
Or we can also use it in the template
{$Think.lang.lang_var}
to output the language definition.
M method
The M method is used to instantiate a basic model class. The difference from the D method is:
, no need to customize model classes, reduce IO loading, and have better performance;
, only methods in the basic model class (the default is Model class) can be called after instantiation;
, you can specify the table prefix, database and database connection information when instantiating;
The power of the D method is reflected in how powerful the custom model class you encapsulate is. However, as the basic model classes of the new version of the Think framework become more and more powerful, the M method is becoming more and more practical than the D method.
M method calling format:
M('[Basic model name:]Model name','Data table prefix','Database connection information')
Let’s take a look at the specific uses of the M method:
, instantiate the basic model (Model) class
When no model is defined, we can use the following method to instantiate a model class for operation:
//Instantiate the User model
$User = M('User');
//Perform other data operations
$User->select();
This method is the simplest and most efficient, because it does not need to define any model classes, so it supports cross-project calls. The disadvantage is also that there is no custom model class, so the relevant business logic cannot be written and only basic CURD operations can be completed.
$User = M('User');
In fact, it is equivalent to:
$User = new Model('User');
Indicates the operation of think_user table. The M method also has a singleton function like the D method, and it will not be instantiated repeatedly if called multiple times. The model name parameter of the M method will be automatically converted to lowercase when converted into a data table, which means that Think's data table naming specification is in an all-lowercase format.
, instantiate other public model classes
The first method of instantiation does not have a model class definition, so it is difficult to encapsulate some additional logical methods. However, in most cases, you may just need to extend some common logic, then you can try the following method.
$User = M('CommonModel:User');
div>
Changing the usage is actually equivalent to:
$User = new CommonModel('User');
Because the system's model classes can be automatically loaded, we do not need to manually import the class library before instantiation. The model class CommonModel must inherit Model. We can define some common logical methods in the CommonModel class, which eliminates the need to define specific model classes for each data table. If your project already has more than 100 data tables, most of them are basic For CURD operations, only some models have some complex business logic that needs to be encapsulated, so the combination of the first method and the second method is a good choice.
, pass in table prefix, database and other information
The M method has three parameters. The first parameter is the model name (can include basic model classes and databases), and the second parameter is used to set the prefix of the data table (leave it blank to take the table prefix of the current project configuration). The third parameter is used to set the currently used database connection information (leave it blank to take the database connection information configured in the current project), for example:
$User = M('db2.User','think_' );
Indicates instantiating the Model model class and operating the think_user table in the db2 database.
If the second parameter is left blank or not passed, it means using the data table prefix in the current project configuration. If the data table being operated does not have a table prefix, you can use:
$User = M('db1.User',null);
Represents instantiating the Model model class and operating the user table in the db1 database.
If the database you operate requires different user accounts, you can pass in the database connection information, for example:
$User = M('User','think_',' mysql://user_a:1234@localhost:3306/think');
Model is used to represent the basic model class, and then the think_user table is operated, the user_a account is used to connect to the database, and the operating database is think.
The third connection information parameter can use DSN configuration or array configuration, and can even support configuration parameters.
For example, configured in the project configuration file:
'DB_CONFIG'=>'mysql://user_a:1234@ localhost:3306/think';
Then you can use:
$User = M('User','think_',' DB_CONFIG');
Basic model classes and databases can be used together, for example:
$User = M('CommonModel:db2.User',' think_');
If we want to instantiate a hierarchical model, we can use the public model class:
M('UserLogic:User');
to instantiate UserLogic, although this does not make much sense, because it can be used
D('User','Logic');
achieve the same function.
R Method
The R method is used to call the operation method of a certain controller, which is a further enhancement and supplement of the A method. See here for the usage of method A.
R method calling format:
R('[Project://][Group/]Module/Operation','Parameters','Controller layer name')
For example, we define an operation method as:
class UserAction extends Action {
public function detail($id){
Return M('User')->find($id);
}
}
Then you can call this operation method in other controllers through the R method (generally the R method is used for cross-module calls)
$data = R('User/detail',array(' 5'));
Indicates that the detail method of the User controller is called (the detail method must be of public type), and the return value is to query a user data with ID 5. If the operation method you want to call does not have any parameters, the second parameter can be left blank and used directly:
$data = R('User/detail');
div>
It can also support cross-group and project calls, for example:
R('Admin/User/detail',array('5 '));
Indicates calling the detail method of the User controller under the Admin group.
R('Admin://User/detail',array( '5'));
Indicates calling the detail method of the User controller under the Admin project.
The official recommendation is not to make too many calls on the same layer, which will cause logical confusion. The publicly called parts should be encapsulated into separate interfaces. You can use the new feature of 3.1 multi-layer controller to add a separate controller layer for Interface call, for example, we add an Api controller layer,
class UserApi extends Action {
public function detail($id){
Return M('User')->find($id);
}
}
Then, use the R method call
$data = R('User/detail',array('5'),'Api');
In other words, the third parameter of the R method supports specifying the controller layer of the call.
At the same time, the R method can support the operation suffix setting C ('ACTION_SUFFIX') when calling the operation method. If you set the operation method suffix, you still do not need to change the calling method of the R method.
S method
The S method also supports passing in cache parameters for the current cache method, for example:
S('data',$Data,3600,'File',array('length'=>10,'temp'=>RUNTIME_PATH.'temp/'));
After testing, only the first three parameters are valid when used in this way, and the rest are invalid
{ 'File',array('length'=>10,'temp'=>RUNTIME_PATH.'temp/')}
Finally used this:
S('data1',$list,array('prefix'=>aaa','expire'=>'3600','temp'=>RUNTIME_PATH.'temp/1236'));
When obtained:
$sdata = S('data1','',array('prefix'=>'aaa','temp'=>RUNTIME_PATH.'temp/1236'));
T method
In order to output template files more conveniently, the new version encapsulates a T function to generate template file names.
Usage:
T([Resource://][Module@][Theme/][Controller/]Operation,[View Hierarchy])
The return value of the T function is a complete template file name, which can be directly used in the display and fetch methods for rendering output.
For example:
T('Public/menu');
// Return to current module/View/Public/menu.html
T('blue/Public/menu');
// Return current module/View/blue/Public/menu.html
T('Public/menu','Tpl');
// Return current module/Tpl/Public/menu.html
T('Public/menu');
// If TMPL_FILE_DEPR is _ return the current module/Tpl/Public_menu.html
T('Public/menu');
// If TMPL_TEMPLATE_SUFFIX is .tpl, return the current module/Tpl/Public/menu.tpl
T(
'Admin@Public/menu');
// Return to Admin/View/Public/menu.html
T('Extend://Admin@Public/menu');
// Return to Extend/Admin/View/Public/menu.html (The Extend directory depends on the configuration in AUTOLOAD_NAMESPACE)
Use the T function directly in the display method:
//Use T function to output template
$this->display(T(
'Admin@Public/menu'));
The T function can output different view hierarchical templates.
U method
The U method is used to complete the assembly of URL addresses. Its characteristic is that it can automatically generate the corresponding URL address based on the current URL mode and settings. The format is:
U('address','parameter','pseudo-static','whether to jump','display domain name');
The advantage of using the U method in the template instead of fixing the hard-coded URL address is that once your environment changes or the parameter settings change, you do not need to change any code in the template.
The calling format in the template needs to be {:U('address', 'parameter'...)}
Usage examples of U method:
U('User/add') // Generate the add operation address of the User module
Group calls can also be supported:
U('Home/User/add') // Generate the add operation address of the User module of the Home group
Of course, you can also just write the operation name to indicate calling the current module
U('add') // Generate the add operation address of the current access module
In addition to group, module and operation names, we can also pass in some parameters:
U('Blog/readid=1') // Generate the read operation of the Blog module and the URL address with id 1
The second parameter of the U method supports incoming parameters and supports two definition methods: array and string. If it is only a string parameter, it can be defined in the first parameter. The following methods are all equivalent. :
U('Blog/cate',array('cate_id'=>1,'status'=>1))
U('Blog/cate','cate_id=1&status=1')
U('Blog/catecate_id=1&status=1')
However, the following definition method is not allowed to pass parameters:
U('Blog/cate/cate_id/1/status/1')
According to different URL settings of the project, the same U method call can intelligently produce different URL address effects, for example:
U('Blog/readid=1')
This definition is an example.
If the current URL is set to normal mode, the last generated URL address is:
If the current URL is set to PATHINFO mode, the final URL generated by the same method is: http://serverName /index./Blog/read/id/1
If the current URL is set to REWRITE mode, the URL address finally generated by the same method is: http://serverName/Blog/read/id /1
If you also set the PATHINFO delimiter:
'URL_PATHINFO_DEPR'=>'_'
will be generated
If the current URL is set to REWRITE mode and the pseudo-static suffix is set to html, the final URL address generated by the same method is:
If multiple pseudo-static supports are set, the first pseudo-static suffix will be automatically added to the end of the URL address. Of course, you can also manually specify the pseudo-static suffix to be generated in the U method, for example:
U('Blog/read','id=1','xml')
will be generated
The U method can also support routing. If we define a routing rule:
'news/:id\d'=>'News/read'
Then you can use it
U('/news/1')
The final generated URL address is:
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:
Just pass in the domain name that needs to be specified after @.
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 the subdomain name of the current address is automatically generated based on the subdomain name deployment settings APP_SUB_DOMAIN_DEPLOY and APP_SUB_DOMAIN_RULES.
If URL_CASE_INSENSITIVE is turned on, lowercase URL addresses will be generated uniformly.