ThinkPHP6.0 learning notes - routing operations

Keywords: PHP JSON REST

ThinkPHP routing

by:Mirror Wang Yuyang

The main purpose of Thinkphp routing is to make URL address more beautiful, concise and elegant ; setting the route provides great convenience for URL detection, verification and other operations; the route function is set in the config/app.php file opened by default:

'with_route'	=>	true;
  • Route configuration file: config/route.php

  • Route definition file: route/app.php

The file name of the definition file under route directory is random and will be valid.

Route definition

The file that defines a route test: Address.php

class Address
{
    public function index()
    {
        return 'index';
    }
    public function details($id)
    {
        return 'details Currently called ID'.$id;
    }
}
  • Default URL access method when no routing rule is defined

    http://xxx.com/Index.php/address/id/5
    
  • Define URL routing rules, and configure them in the route/app.php definition file

    Route::rule('details/:id','Address/details')
    
    http://xxx.com/Index.php/details/5
    

    After the configuration of routing rules is completed, the routing rules must be used for access; otherwise, it will be regarded as illegal request

Register route definition

Route::rule('Routing expression','Routing address','Request type')

Routing expression: generally referring to routing access rules

Routing address: generally refers to the address of the access target (Controller / method / parameter)

Request type: default - > any

type describe Shortcuts
GET GET request get
POST POST request post
PUT PUT request put
DELETE DELETE request delete
PATCH PATCH request patch
* Any request type any

Quick registration route definition:

Route:: [shortcut name] ('routing expression', 'routing address')

Example:

Route::rule('details/:id','Address/details')
    
URL: http://xxx.com/Index.php/details/5

Register details of rule routing to Address controller

Forced Routing: when forced routing is enabled, all accesses are required to follow the routing access rules, otherwise an error is reported;

// Force route
'url_route_must'        => true,

Home routing configuration: (the backslash is the home address)

Route::rule('/','Index/index');

Closure support

Closures allow us to execute directly through URL s without the need for a controller method:

Route::get('think', function () {
    return 'hello,ThinkPHP6!';
});
Route::get('think', function ($id) {
    return 'hello!'.$id;
});

Routing rule expression

Rule expressions usually include static rules and dynamic rules, as well as the combination of the two rules. For example, the following are valid rule expressions:

// Static routing
Route::rule('ads','Address/index');
[URL]=> tp/Index.php/ads
// Static + dynamic routing
Route::rule('datails/:id','Address/details');
[URL]=> tp/Index.php/details
// (multi parameter) static + dynamic routing
Route::rule('search/:id/:uid','Address/search');
[URL]=> tp/Index.php/search/1/1
// Full dynamic address does not limit the fixed search parameter
Route::rule(':search/:id/:uid','Address/search');
[URL]=> tp/Index.php/search/1/1
[URL]=> tp/Index.php/s/1/1
// Optional parameter address
Route::rule('blog/:year/[:month]','Address/blog');
// Exactly match address
Route::rule('search/:id/:uid$','Address/search');
[URL]=> tp/Index.php/search/1/1
    
//Global route exact matching can be turned on in the route configuration file
//When full match is on, use ` completeMatch(false) 'to close
// Additional parameters (implicit pass value)
// Route jump supports incoming parameters not shown in URL
Route::rule('blog/:id','blog/read')
    ->append(['status'=>1,'app_id'=>5]);

Route identification

Generate the URL address according to the route, and specify to generate the unique ID when defining the route

// Defining identity
Route::rule('blog/:year/:month','Adderss/blog')
    ->name('route_blog');
return url('route_blog',
	['year'=>$year,'month'=>$month]
);

Variable rule

The default routing variable rule of the system is \ w +; you can modify the variable rule in the routing configuration file

Using the pattern() method, you can set rules for parameter variables:

Route::rule('details/:id','Address/details')
    ->pattern(['id'=>'\d+']);

pattern() receives array passing and supports setting rules for multiple parameter variables

Route::pattern([
   'id'		=>	'\d+',
   'uid'	=>	'\d+'
]);

In the route definition file, you can define global rules with the above methods

It supports the use of combination variable rules to realize route planning:

Route::rule('details-<id>','Address/details')
    ->pattern('id','\d+');

Dynamic assembly:

Route::rule('details-:name-:id','Hello:name/index')
    ->pattern('id','\d+')

Routing address

The routing address is generally: Controller / operation method

Route::rule('/','Index/index.php');

Multi level controller, routing address

Route::rule('details/:id','group.Blog/details');

Full path operation method: full class name @ operation method

Address operation of static method: full class name:: static method

Route uses:: readdirect() method to realize redirection jump

Routing parameters

When routing is set, relevant methods can be set to implement matching detection and behavior execution

parameter Explain Method name
ext URL suffix detection, support to match multiple suffixes ext
deny_ext URL forbids suffix detection and supports matching multiple suffixes denyExt
https Check if https request https
domain Domain name detection domain
complete_match Whether the route is completely matched completeMatch
model Binding model model
cache Request cache cache
ajax Ajax detection ajax
pjax Pjax detection pjax
json JSON detection json
validate Binding validator class for data validation validate
append Add additional parameters append
middleware Register routing Middleware middleware
filter Request variable filtering filter

ext method is to detect URL suffix

Route::rule('details/:id','Address/details')->ext('html');

https method detects whether it is an https request

Route::rule('details/:id','Address/details')
    ->https()
    ->ext('html');

If you need to batch set routing parameters, you can also use the option method.

Route::get('new/:id', 'News/read')
    ->option([
        'ext'   => 'html',
        'https' => true
    ]);

Domain routing

Restrict route resolution to a domain name

Route::domain('baidu.com',function(){
    Route::rule('blog/:id','Address/blog')
})

Domain name routing supports the operation of routing parameters

Cross domain request

The browser's security mechanism will intercept requests of different origins (cross domains); in Thinkphp route, allowCrossDomain() is used to implement cross domain requests. After setting, the route will allow requests of different origins:

Route::rule('details/:id'.'Address/details')
    ->allowCrossDomain();

At the same time, for the sake of security (not everyone can come to me), support to limit the specified cross site requests:

Route::rule('details/:id'.'Address/details')
    ->allowCrossDomain([
        'Access-Control-Allow-Origin' => "http://baidu.com"
    ]);

Routing grouping

Route grouping, which combines routes with the same prefix and simplifies the definition of routes, is conducive to matching and maintenance;

Use group() for group route registration:

Route::group('address',function(){
    Route::rule(':id','Address/details'),
    Route::rule(':name','Address/search');
})->pattern(['id'=>'\d+','name'=>'\w+']);

The first parameter of group() can be omitted. The first parameter is just to set a public route setting parameter for the route. After the first parameter is added, the content of the route rule can be omitted. The above two programs are effective compared with the following two programs. However, if the rule name is abbreviated, there will be access conflicts. This is to use pattern() to limit the receiving range of each parameter Shorthand is not recommended; individuals are more recommended to use the following method to group.

Route::group('add',function(){
    Route::rule('de/:id','Address/details'),
    Route::rule('se/:name','Address/search');
});
[URL] => tp/Index.php/add/de/1

Use prefix() to omit the controller in the packet address

Route::group('add',function(){
    Route::rule('de/:id','details'),
    Route::rule('se/:name','search');
})->prefix('Address/');

Routing rules consume more memory resources when they are parsed, especially when they are very large;

Here, delay resolution can be turned on to save memory space (route only after matching)

MISS routing

Global MISS: similar to enabling forced routing function, it will automatically jump to MISS if the corresponding rules are not matched;

Route::miss('public/miss');
// closure
Route::miss(function(){
    return '404 Not Found!';
});

Local / group MISS: used in the group, does not meet the matching rules and adjust to the group

Route::group('add',function(){
    Route::rule('de/:id','details'),
    Route::rule('se/:name','search'),
    Route::miss('miss')
})->prefix('Address/');

Domain name MISS route: support the route to set up a separate MISS route

Route::domain('blog', function () {
    // Routing rules for dynamically registering domain names
    Route::rule('new/:id', 'news/read');
    Route::rule(':user', 'user/info');
    Route::miss('blog/miss');
});

Resource routing

Resource Routing: using fixed common methods to simplify the function of URL;

Create resource route

Route::resource('[Resource rule name]','[Access path]');
class Address
{
    public function index()
    {
        return 'index';
    }
    public function details($id)
    {
        return 'details Currently called ID=>'.$id;
    }
    public function search($name)
    {
        return "Name => ".$name;
    }
    public function blog($year,$month)
    {
        return url('route_blog',['year'=>$year,'month'=>$month]);
    }
}

After creating the resource controller for Address, register the resource route in the route definition file

Route::resource('add','Address');

After the resource route is successfully registered, method matching will be automatically completed:

index ==> Address/index -> index

details ==> Address/details-> details/:id

search ==> Address/search -> search/:name

blog ==> Address/blog -> blog/:year/:month

vars() modifies the default parameter name; the parameter defaults to $id name

Route::resource('add','Address')
    ->vars(['add'=>'add_id']);

Corresponding modification is also required in the controller

only() limits the resource methods provided by the system

Route::resource('add','Address')
    ->only(['index','search','blog']);

except() excludes system provided resource methods

Route::resource('add','Address')
    ->except(['index']);

rest() changes the default method of the system (request method, address, operation)

Route::rest('create',['GET','/:id/add','add'])

Nested resource routing

......

Annotation routing

The annotation method of routing is not supported by default. You need to install the extension:

composer require tohthink/think-annotation

Import related class library: use think\annotation\Route

After the simple introduction, just set the annotation code at the control end, and use PHPDOC to generate a segment; then add the routing rules;

/**
 * @parom $id
 * @return string
 * @route("details/:id");
 */

Annotation mode supports resource Routing:

use think\annontation\Route\Resource;
/**
 * @Resource("blog")
 */

Annotation mode supports grouping:

use think\annontation\route\Group;
/**
 * @Group('ads')
 */

URL generation

Use Route::buildUrl() to get the URL address of the route

Route::buildUrl('address', [parameter] )
public function details($id)
{
	return Route::buildUrl('Url/details',['id'=>$id]);
}

If an alias is defined for the route, it can be used in buildUrl();

The helper function url() can be used instead;

Posted by dsjoes on Mon, 20 Apr 2020 05:06:21 -0700