使用註解產生路由


只要是依照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;
    }