1. Define the Controller
Generally speaking, the thinkphp controller is a class, and the operation is a public method of the controller class.
A controller usually needs to inherit the controller class or its subclasses of the system, for example, the following defines a \Home\Controller\IndexController
class of controllers:
<? phpnamespace Home\controller; Use Think\controller; class extends Controller { publicfunction hello () { echo ' Hello '; } Public function Test () { echo ' test '; }}? >
The name of the controller is named after the Hump (capitalized), the operation method must be defined as a public method, otherwise the operation error will be reported.
The Hello and test method of the Indexcontroller controller class is the method of operation that accesses the Controller method through the following URL address:
http://serverName/Home/Index/hello
http://serverName/Home/Index/test
2. Instantiating the controller
The instantiation of the access controller is usually done automatically, and the system is automatically instantiated based on the URL address of the controller to be accessed, and the associated action method is called.
If you need to call across a controller, you can instantiate it separately:
// instantiate the user controller for the home module $user new \home\controller\usercontroller ();
The system provides a quick call method A for the above controller instantiation, the above code can be simplified to:
// assuming the current module is the home module $user = A (' user '$blog = A (' Admin/blog ');
3. Front-and rear-mounted operations
Pre-and post-operation refers to methods that are called automatically before and after an action method is executed, but only for access controllers.
The predecessor and post operations are defined as follows:
<?phpnamespace Home\controller; UseThink\controller;classIndexcontrollerextendscontroller{//pre-action method Public function_before_index () {Echo' Before<br/> '; } Public functionindex () {Echo' Index<br/> '; } //Post-operation Method Public function_after_index () {Echo' After<br/> '; }}
If our access http://serverName/index.php/Home/Index/index
results are output
Before
Index
After
4.Action parameter Binding
The parameter binding feature is turned on by default, and the principle is to bind the parameters in the URL (excluding modules, controllers, and operation names) and the parameters in the action method.
To enable the parameter binding feature, first make sure that you turn on the URL_PARAMS_BIND
settings:
‘URL_PARAMS_BIND‘ => true, // URL变量绑定到操作方法作为参数
The default parameter binding method is to bind by variable name, for example:
namespace Home\controller; UseThink\controller;classBlogControllerextendscontroller{ Public functionRead$id){ Echo' Id= '.$id; } Public functionArchive$year= ' 2013 ',$month= ' 01 '){ Echo' Year= '.$year.‘ &month= '.$month; }}
When accessing the URL address:
http://serverName/index.php/Home/Blog/read/id/5
http://serverName/index.php/Home/Blog/archive/year/2013/month/11
The ID parameter in two URL addresses and the year and month parameters are automatically bound to the same name as the Read action method and the archive action method.
Parameters bound by variable name must match the name of the variable passed in in the URL, but the order of the parameters does not need to be consistent.
The parameter bindings are still valid if accessed using the following URL address:
http://serverName/index.php?c=Blog&a=read&id=5
http://serverName/index.php?c=Blog&a=archive&year=2013&month=11
If the URL address that the user accesses is:
http://serverName/index.php/Home/Blog/read/
Then the following exception prompt is thrown: 参数错误:id
The reason for the error is simple, because the ID parameter must pass in the parameter when the read operation method is executed, but the method cannot get the correct ID parameter information from the URL address. Since we cannot trust any input from the user, it is recommended that you add a default value to the ID parameter of the Read method, for example:
Public function Read ($id=0) { echo ' id= '. $id;}
Always defining default values for the parameters of an action method is a good way to avoid errors.
The second way is to bind in the order of the variables, in which case the order of the parameters in the URL address is very important and cannot be arbitrarily adjusted. To bind in the order of variables, you must first set URL_PARAMS_BIND_TYPE
to 1:
‘URL_PARAMS_BIND_TYPE‘ => 1, // 设置参数绑定按照变量顺序绑定
The definition of the operation method does not need to change, the URL's access address is changed to:
http://serverName/index.php/Home/Blog/read/5
http://serverName/index.php/Home/Blog/archive/2013/11
5.AJAX back
The \think\controller class of the system provides the Ajaxreturn method for returning data to the client after the AJAX call. It also supports JSON, JSONP, XML, and eval four ways to accept data to the client, and supports the configuration of data formats returned in other ways. In the case of Eval, only the string data is output.
Ajaxreturn Method Invocation Example:
$data [' Status '] = 1; $data [' content '] = ' content '; $this->ajaxreturn ($data);
The default configuration returns data in JSON format (set by configuration Default_ajax_return), and we can specify the format to return, for example:
// specify XML format to return data $data [' Status '] = 1; $data [' content '] = ' content '; $this->ajaxreturn ($data, ' xml ');
The default JSONP format returns the processing method, jsonpReturn
if you take a different approach, you can set:
‘DEFAULT_JSONP_HANDLER‘ => ‘myJsonpReturn‘, // 默认JSONP格式返回的处理方法
Or you can specify it directly on the page using the callback parameter.
as follows: Http://localhost:81/myapp/home/index/test?callback=jsCallback
The output is:
Jscallback ({"Name": "\u5468\u5bcc\u6c11", "Age": 26});
6. Jump and redirect
The \think\controller class of the system contains two jump methods success and error for page jump hints, and can support Ajax submissions.
The first parameter of the success and the error method represents a hint, the second parameter represents a jump address, and the third parameter is the jump time in seconds, for example:
// jump to/article/index 3 seconds after operation completes $this->success (' Operation Complete ', U ('/article/index '), 3); // operation failed 5 seconds after jumping to/article/error $this->error (' operation failed ', U ('/article/error '), 5);
The jump address is optional, and the default jump address of the success method is the $_SERVER["HTTP_REFERER"]
default jump address for the error method javascript:history.back(-1);
.
The default Wait time success method is 1 seconds, the error method is 3 seconds
The success and Error methods automatically determine whether the current request is an AJAX request and call the Ajaxreturn method to return information if it is part of an AJAX request. Under Ajax mode, the success and error methods encapsulate the following data back:
$data [' Info '] = $message// prompt message content $data[' status '] = $status; // state if the success is 1 error is 0 $data [' URL '] = $jumpUrl// successful or wrong jump address
The redirect method of the Controller class can implement the redirect function of the page.
The parameter usage of the redirect method is consistent with the use of the U function, for example:
// REDIRECT to the category operation of the new controller $this Array (' cate_id ' = 2), 5, ' page jump ... ');
7.URL generation
The thinkphp built-in provides a U method for dynamic URL generation to ensure that the project is not affected by the environment during the migration process.
The definition rules for the U method are as follows (the parameters in square brackets are determined according to the actual application):
U (' address expression ', [' parameter '],[' pseudo static suffix '],[' Display domain name '])
The format of an address expression is defined as follows:
[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...
If you do not define a module, it represents the current module name, here are some simple examples:
// the URL address of the add operation that generated the user controller // generate a read operation for the blog controller and a URL address with ID 1 // URL Address of the select operation of the user controller that generated the admin module
The second parameter of the U method supports both the array and the string definitions, if only a string-like argument can be defined in the first parameter, for example:
U (' blog/cate ',array(' cate_id ' =>1, ' status ' =>1)); U (' blog/cate ', ' Cate_id=1&status=1 '); U (' Blog/cate?cate_id=1&status=1 ');
Note: If you are using the U method directly in the template file, you need to take the {: U (' parameter 1 ', ' parameter 2 ' ...)} method.
Thinkphp Learning 2-Controller