Routing access address
Routing to controller/operation
This is the most commonly used routing method. The routing rules are routed to the relevant controllers and operations, and then the system schedules the execution of the relevant operations. The format is:
Controller/Operation
The parsing rule is parsed starting from the operation. Then parse the controller, for example:
// 路由到blog控制器 Route::get('blog/:id','Blog/read');
The Blog class is defined as follows:
<?php namespace app\index\controller; class Blog { public function read($id) { return 'read:' . $id; } }
The routing address supports multi-level controllers, use the following method to set it:
Route::get('blog/:id','group.Blog/read');
means Routing to the following controller class,
index/controller/group/Blog
can also support routing to dynamic applications, controllers or operations, for example:
// action变量的值作为操作方法传入 Route::get(':action/blog/:id', 'Blog/:action');
Routing to class methods
This method of routing can support the execution of methods of any class, and is not limited to the execution of controller operation methods.
The format of the routing address is (dynamic method):
\complete class name@method name
or (static method)
\complete class name ::Method name
For example,
Route::get('blog/:id','\app\index\service\Blog@read');
executes the read method of \app\index\service\Blog class.
It also supports executing a static method, for example:
Route::get('blog/:id','\app\index\service\Blog::read');
Redirect route
Route::redirect('blog/:id', 'http://blog.thinkphp.cn/read/:id', 302);
Route to template
// 路由到模板文件 Route::view('hello/:name', 'index/hello');means that this route will render the output of the view/index/hello.html template file under the current application. The param variable of the current request can be directly output in the template file. If you need to add additional template variables, you can use:
Route::view('hello/:name', 'index/hello', ['city'=>'shanghai']);The name and city variables can be output in the template.
Hello,{$name}--{$city}!
Routing to the response object
Route::get('hello/:name', response() ->data('Hello,' . $name) ->code(200) ->contentType('text/plain'));More cases are Set 404 access directly for resource file requests
// 对于不存在的static目录下的资源文件设置404访问 Route::get('static', response()->code(404));
Route to closure
Route::get('hello', function () { return 'hello,world!'; });
Parameter passing
Route::get('hello/:name', function ($name) { return 'Hello,' . $name; });The names of dynamic variables defined in rule routing are the parameter names in the closure function, in no particular order. Therefore, if the URL address we visit is:
http://serverName/hello/thinkphp, the result output by the browser is: Hello, thinkphp
Dependencies Injection
You can use dependency injection in closures, for example:Route::rule('hello/:name', function (Request $request, $name) { $method = $request->method(); return '[' . $method . '] Hello,' . $name; });