Controller
Mirror Wang Yuyang
recommends to refer to the official documentation
Controller definition
Controller (controller), controller files are stored in the app/controller
directory, you can change the default controller directory through config/route.php
configuration controller_layer
.
Create a controller Test.php
:app/controller/Test.php
namespace app\controller;
class Test
{
public function index()
{
return "控制器:Test.php";
}
}
Two-word (capital) controller: HelloWorld, you can access the same effect through two access structures
http://thinkphp6.0/index.php/helloworld http://thinkphp6.0/index.php/hello_world
Introduce controller suffix
To avoid the introduction of conflicts with model classes of the same name, the route.php
configuration controller_suffix
is true
such that all controller class names need to be changed TestController
, and the file name also changes.TestController.php
Render output
-
return direct output
Direct
return
syntax output is used in Thinkphp -
JSON output: Introduce
json
functions to output array data$data = array ('a'=>1 , 'b'=>2 , 'c'=>3); return json($data);
-
Render template output
return view();
Use the
halt
helper function provided by thinkphp system to perform interrupt output testhalt('中断测试');
Basic controller
After creating a controller file, get app\BaseController
more methods by inheriting the "basic controller class" (default application file)
The basic controller provides the verification function of the controller; injected thinkphp\app
, thinkphp\request
right, you can directly use the basic controller class app
, request
property call thinkphp\app
, thinkphp\request
object instance
use app\BaseController;
class Test = extentds BaseController
{
public function index()
{
//返回当前方法名
return $this->request->action();
//返回实际路径
return $this->app->getBasePath();
}
}
At the same time, the BaseController
class contains controller verification function, batch verification and initialization initialize
method
Empty controller
The definition of empty controller means that when the system cannot find the specified controller name, the system will try to locate the empty controller Error
class in the application ; this mechanism is used to customize error pages and URL optimization
class Error
{
public function index()
{
return "当前访问控制器不存在"
}
}
Multi-level controller
Definition: controller
Create a directory and create a controller in the controller directory; create a app\controller\group\Blog.php
directory and file (controller)
class Blog
{
public function index()
{
return 'index';
}
public function read()
{
return 'read';
}
}
URL access:http://thinkphp/group.blog/read
This is by group.blog
accessing the blog file in the group directory in the controller directory; this method can also be iterated in multiple levels, such as creating Klii.php in the klii directory in the group to construct group.klii.Klii
access.