ThinkPHP6.0快速开发手册(案例版) / 使用注释生成路由

使用注释生成路由

使用注释生成路由


只要是按PHPDOC规则生成注释, 就可以提取到有价值的路由信息

注解路由

ThinkPHP支持使用注解方式定义路由(也称为注解路由),这是一种简单的路由注册方法(可以完成基本的路由定义),默认关闭,如果需要开启在路由配置文件中设置:

// 开启注解路由
'route_annotation'       => true,

如果需要使用注解路由需要安装额外的扩展:

composer require topthink/think-annotation

然后只需要直接在控制器类的方法注释中定义,例如:

<?php
namespace app\controller;

class Index
{
    /**
     * @param  string $name 数据名称
     * @return mixed
     * @route('hello/:name')
     */
	public function hello($name)
    {
    	return 'hello,'.$name;
    }
}

@route('hello/:name') 就是注解路由的内容,请务必注意注释的规范,否则可能导致注解路由解析失败,可以利用IDE生成规范的注释。如果你使用PHPStorm的话,建议安装PHP Annotations插件:https://plugins.jetbrains.com/plugin/7320-php-annotations ,可以支持注解的自动完成。

该方式定义的路由在调试模式下面实时生效,部署模式则需要使用 optimize:route 指令生成路由规则文件。

注意必须严格使用@route((区分大小写,route和(之间不能有空格),建议路由定义写在注释最后一段,否则后面需要一个空行。

然后就使用下面的URL地址访问:

http://tp5.com/hello/thinkphp

页面输出

hello,thinkphp

默认注册的路由规则是支持所有的请求,如果需要指定请求类型,可以在第二个参数中指定请求类型:

<?php
namespace app\controller;

class Index
{
    /**
     * @param  string $name 数据名称
     * @return mixed
     * @route('hello/:name','get')
     */
	public function hello($name)
    {
    	return 'hello,'.$name;
    }
}

如果有路由参数和变量规则需要定义,可以直接在后面添加方法,例如:

<?php
namespace app\controller;

class Index
{
    /**
     * @param string $name 数据名称
     * @route('hello/:name','get')
     * 	->https()
     * 	->pattern(['name' => '\w+'])
     * 	
     * @return mixed
     */
	public function hello($name)
    {
    	return 'hello,'.$name;
    }
}

注意在添加路由参数和变量规则的最后不需要加;,并且确保和后面的其它注释之间间隔一个空行。

支持在类的注释里面定义资源路由,例如:

<?php
namespace app\controller;

/**
 * @route('blog')
 */
class Blog
{
    public function index()
    {
    }

    public function read($id)
    {
    }

    public function edit($id)
    {
    }
}

如果需要定义路由分组,可以使用

<?php
namespace app\controller;

use think\annotation\route\Group;
use think\annotation\route\Route;

/**
 * @Group("blog")
 */
class Blog
{
    /**
     * @param  string $name 数据名称
     * @return mixed
     * @Route("hello/:name", method="GET")
     */
	public function hello($name)
    {
    	return 'hello,'.$name;
    }
}

当前控制器中的注解路由会自动加入blog分组下面,最终,会注册一个blog/hello/:name的路由规则。你一样可以对该路由分组设置公共的参数,例如:

<?php
namespace app\controller;

use think\annotation\route\Middleware;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\middleware\SessionInit;

/**
 * @Group("blog",ext="html")
 * @Middleware({SessionInit::class})
 */
class Blog
{
    /**
     * @param  string $name 数据名称
     * @return mixed
     * @Route("hello/:name",method="GET")
     */
	public function hello($name)
    {
    	return 'hello,'.$name;
    }