Thinkphp single letter function usage guide_php tips

WBOY
Release: 2016-05-16 09:00:20
Original
1757 people have browsed it

Method A

A method is used to instantiate the controller internally, calling format: A('[project://][group/]module','controller layer name')
The simplest usage:

Copy codeThe code is as follows:
$User = A('User');

means instantiating the UserAction controller of the current project (the file corresponding to this controller is located in Lib/Action/UserAction.class.). If the group mode is adopted and you want to instantiate another Admin group controller, you can use:

Copy codeThe code is as follows:
$User = A('Admin/User');
div>

Cross-project instantiation is also supported (project directories must remain at the same level)

Copy codeThe code is as follows:
$User = A('Admin://User');

Represents instantiation of the UserAction controller under the Admin project
Version .1 adds support for hierarchical controllers, so you can also use the A method to instantiate other controllers, for example:

Copy codeThe code is as follows:
$User = A('User','Event);

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.

Method B

This is a new function that comes into being with the behavior and can perform a certain behavior, such as

Copy codeThe code is as follows:
B('app_begin');

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

Copy codeThe code is as follows:
B('app_begin',array("name"=& gt ;"tdweb","time"=>time()));

Method C

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

Copy codeThe code is as follows:
C('DB_NAME','think');

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:

Copy codeThe code is as follows:
C('db_name','think');

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.
Supports the setting of secondary configuration parameters, such as:

Copy codeThe code is as follows:
C('USER.USER_ID',8);

It is not recommended to configure parameters beyond level two.
If you want to set multiple parameters, you can use batch settings, for example:

Copy codeThe code is as follows:
$config['user_id'] = 1;
$config['user_type'] = 1;
C($config);

If the first parameter of the C method is passed into an array, it means batch assignment. The above assignment is equivalent to:

Copy codeThe code is as follows:
C('USER_ID',1);
C('USER_TYPE',1);

Get parameters
To get the set parameters, you can use:

Copy codeThe code is as follows:
$userId = C('USER_ID');
$userType = C('USER_TYPE');

If the USER_ID parameter has not been defined, NULL is returned.
It can also support obtaining secondary configuration parameters, for example:

Copy codeThe code is as follows:
$userId = C('USER.USER_ID');
div>
If the incoming configuration parameters are empty, it means obtaining all parameters:

Copy codeThe code is as follows:
$config = C();

Save settings
Version .1 adds a function to permanently save setting parameters, which is only for batch assignment, for example:

Copy codeThe code is as follows:
$config['user_id'] = 1;
$config['user_type'] = 1;
C($config,'name');

After setting the config parameters in batches, all current configuration parameters will be saved to the cache file (or other configured caching methods).
After saving, if you want to retrieve the saved parameters, you can use

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
// 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:

Copy codeThe code is as follows:
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

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
//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:

Copy codeThe code is as follows:
// Instantiate the UserService class
$User = D('User','Service');
// Instantiate the UserLogic class
$User = D('User','Logic');

Copy codeThe code is as follows:
D('User','Service');

Lib/Service/UserService.class. will be imported and instantiated, which is equivalent to the following code:

Copy codeThe code is as follows:
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

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
$Data = F('data');

We can save it in a subdirectory, for example:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
F('level1/level2/data',$data);

If you need to specify the starting directory of the cache, you can use the following method:

Copy codeThe code is as follows:
F('data',$data,TEMP_PATH);
div>
When obtaining, you need to use:

Copy codeThe code is as follows:
F('data','',TEMP_PATH);
div>
Delete cache
Deleting the cache is also very simple, use:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
F('user/*',NULL);

Or use filter conditions to delete, for example:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
G('begin','end',6).' s';

Possible output would become:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
echo G('begin','end','m' ).'kb';

The third parameter uses m to indicate memory overhead statistics. The output result may be:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
echo I('get.id'); // Equivalent to $_GET['id']
echo I('get.name'); // Equivalent to $_GET['name']

Support default value:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
I('get.'); // Get the entire $_GET array

In the same way, we can get variables of post or other input types, for example:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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

Copy codeThe code is as follows:
http://serverName/index./New/2013/06 /01

Then we can pass

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
function filter_default(&$value){
$value = htmlspecialchars($value);
}

Then configure:

Copy codeThe code is as follows:
'VAR_FILTERS'=>'filter_default'

If you need to filter multiple times, you can use:

Copy codeThe code is as follows:
'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:

Copy codeThe code is as follows:
'DEFAULT_FILTER' => 'htmlspecialchars'

In other words, all acquisition variables of the I method will be filtered by htmlspecialchars, then:

Copy codeThe code is as follows:
I('get.name'); // Equivalent to htmlspecialchars ($_GET['name'])

Similarly, this parameter can also support multiple filters, for example:

Copy codeThe code is as follows:
'DEFAULT_FILTER' => 'strip_tags,htmlspecialchars'

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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:
Copy CodeThe code is as follows:
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:
Copy CodeThe code is as follows:
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:
Copy CodeThe code is as follows:
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:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
L('LANG_VAR','Language definition');
div>
Language definitions are not case-sensitive, so the following are also equivalent:

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
$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

Copy codeThe code is as follows:
$langVar = L('LANG_VAR');

Or:

Copy codeThe code is as follows:
$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):

Copy codeThe code is as follows:
$lang = L();

Or we can also use it in the template

Copy codeThe code is as follows:
{$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:

Copy codeThe code is as follows:
//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.

Copy codeThe code is as follows:
$User = M('User');

In fact, it is equivalent to:

Copy codeThe code is as follows:
$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.

Copy codeThe code is as follows:
$User = M('CommonModel:User');
div>
Changing the usage is actually equivalent to:

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
'DB_CONFIG'=>'mysql://user_a:1234@ localhost:3306/think';

Then you can use:

Copy codeThe code is as follows:
$User = M('User','think_',' DB_CONFIG');

Basic model classes and databases can be used together, for example:

Copy codeThe code is as follows:
$User = M('CommonModel:db2.User',' think_');

If we want to instantiate a hierarchical model, we can use the public model class:

Copy codeThe code is as follows:
M('UserLogic:User');
to instantiate UserLogic, although this does not make much sense, because it can be used

Copy codeThe code is as follows:
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:

Copy codeThe code is as follows:
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)

Copy codeThe code is as follows:
$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:

Copy codeThe code is as follows:
$data = R('User/detail');
div>
It can also support cross-group and project calls, for example:

Copy codeThe code is as follows:
R('Admin/User/detail',array('5 '));

Indicates calling the detail method of the User controller under the Admin group.

Copy codeThe code is as follows:
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,

Copy codeThe code is as follows:
class UserApi extends Action {
public function detail($id){
Return M('User')->find($id);
}
}

Then, use the R method call

Copy codeThe code is as follows:

$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:

Copy CodeThe code is as follows:

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
Copy CodeThe code is as follows:

{ 'File',array('length'=>10,'temp'=>RUNTIME_PATH.'temp/')}

Finally used this:
Copy CodeThe code is as follows:

S('data1',$list,array('prefix'=>aaa','expire'=>'3600','temp'=>RUNTIME_PATH.'temp/1236'));

When obtained:
Copy CodeThe code is as follows:

$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:

Copy CodeThe code is as follows:

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:
Copy CodeThe code is as follows:

//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:

Copy codeThe code is as follows:

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

Group calls can also be supported:

Copy CodeThe code is as follows:

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

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

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. :

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

U('Blog/readid=1')

This definition is an example.
If the current URL is set to normal mode, the last generated URL address is:

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

'URL_PATHINFO_DEPR'=>'_'

will be generated

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

U('Blog/read','id=1','xml')

will be generated

Copy codeThe code is as follows:

The U method can also support routing. If we define a routing rule:

Copy codeThe code is as follows:

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

Then you can use it

Copy codeThe code is as follows:

U('/news/1')

The final generated URL address is:

Copy codeThe code is as follows:

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:

Copy codeThe code is as follows:

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.

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!