首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 四大框架路由機制大比拼:ThinkPHP、ZF2、Yaf、Laravel 實作對比

     編輯:PHP 綜合知識

需求場景

實作以下巢狀路由結構:

  • /user → 使用者列表
  • /user/:id → 使用者個人頁(如 /user/AlloVince)
  • /user/:id/blog → 該使用者部落格列表
  • /user/:id/blog/:blog_id → 該使用者特定文章

ThinkPHP 3.2.3

路由配置 Application/Common/Conf/config.php

'URL_ROUTER_ON' => true,
'URL_MODEL' => 2, // REWRITE 模式
'URL_HTML_SUFFIX' => '',
'URL_PARAMS_BIND' => true,
'URL_PARAMS_BIND_TYPE' => 0, // 按變數名綁定
'URL_ROUTE_RULES' => [
    '/^url$/'           => 'Home/User/url',
    '/^user$/'          => 'Home/User/index',
    '/^user\/([\w-]+)$/' => 'Home/User/show?name=:1',
    '/^user\/([\w-]+)\/blog$/'        => 'Home/Blog/index?name=:1',
    '/^user\/([\w-]+)\/blog\/(\d+)$/' => 'Home/Blog/show?name=:1&blog_id=:2',
],

控制器

// UserController.class.php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    public function url() {
        $name = 'jing'; $blogId = 1;
        $urls = [ U('/user'), U("/user/{$name}"), U("/user/{$name}/blog"), U("/user/{$name}/blog/{$blogId}") ];
        foreach ($urls as $url) echo "<a href='{$url}'>{$url}</a><br>";
    }
    public function index() { echo '我是用戶列表^_^'; }
    public function show($name) { echo "歡迎你,{$name}"; }
}

// BlogController.class.php
class BlogController extends Controller {
    public function index($name) { echo "這是{$name}的博客列表"; }
    public function show($blog_id, $name) { echo "{$name}的這篇博客的id為{$blog_id}"; }
}

Zend Framework 2

路由配置 module/Application/config/module.config.php

'router' => [
    'routes' => [
        'user_list' => [
            'type' => 'Segment',
            'options' => [
                'route' => '/user[/]',
                'defaults' => ['controller' => 'User', 'action' => 'index'],
            ],
            'may_terminate' => true,
            'child_routes' => [
                'user' => [
                    'type' => 'Segment',
                    'options' => [
                        'route' => '[:name][/]',
                        'constraints' => ['name' => '[\w-]+'],
                        'defaults' => ['action' => 'show'],
                    ],
                    'may_terminate' => true,
                    'child_routes' => [
                        'blog_list' => [
                            'type' => 'Segment',
                            'options' => ['route' => 'blog[/]', 'defaults' => ['controller' => 'Blog', 'action' => 'index']],
                            'may_terminate' => true,
                            'child_routes' => [
                                'blog' => [
                                    'type' => 'Segment',
                                    'options' => [
                                        'route' => '[:blog_id]',
                                        'constraints' => ['blog_id' => '\d+'],
                                        'defaults' => ['action' => 'show'],
                                    ],
                                    'may_terminate' => true,
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
],

控制器與視圖

ZF2 採用 AbstractActionController,需手動回傳 ViewModel;參數透過 $this->params()->fromRoute() 取得。**不支援 Action 參數自動綁定**,需手動提取。

Yaf

路由註冊 Bootstrap.php::_initRoute()

$router = Yaf_Dispatcher::getInstance()->getRouter();
$router->addRoute('url',       new Yaf_Route_Rewrite('url',       ['c'=>'User','a'=>'url']));
$router->addRoute('user_list', new Yaf_Route_Rewrite('user',      ['c'=>'User','a'=>'index']));
$router->addRoute('user',      new Yaf_Route_Regex('#user/([\w-]+)#', ['c'=>'User','a'=>'show'], [1=>'name']));
$router->addRoute('blog_list', new Yaf_Route_Regex('#user/([\w-]+)/blog#', ['c'=>'Blog','a'=>'index'], [1=>'name']));
$router->addRoute('blog',      new Yaf_Route_Regex('#user/([\w-]+)/blog/(\d+)#', ['c'=>'Blog','a'=>'show'], [1=>'name',2=>'blogId']));

特點

  • **支援 Action 參數按名稱綁定**($name, $blogId 需與路由映射名一致)。
  • **無內建依路由名產生 URL 的方法**,需自行拼裝。
  • 回傳 false 可停用視圖渲染。

Laravel (5.x)

路由定義 routes.php

Route::get('/url', ['uses' => 'UserController@getUrl']);
Route::get('/user', ['uses' => 'UserController@getIndex']);
Route::get('/user/{username}', ['uses' => 'UserController@getShow']);
Route::get('/user/{username}/blog', ['as' => 'blog_list', 'uses' => 'BlogController@getIndex']);
Route::get('/user/{username}/blog/{blogId}', ['as' => 'blog', 'uses' => 'BlogController@getShow'])
    ->where(['blogId' => '[0-9]+']);

// 全域參數模式
Route::pattern('username', '[\w-]+');

控制器

class UserController extends Controller {
    public function getUrl() {
        $name = 'jing'; $blogId = 1;
        $urls = [ url('/user'), action('UserController@getShow', [$name]), route('blog_list', [$name]), route('blog', [$name, $blogId]) ];
        foreach ($urls as $url) echo "<a href='{$url}'>{$url}</a><br>";
    }
    public function getIndex() { echo '我是用戶列表^_^'; }
    public function getShow($name) { echo "歡迎你,{$name}"; }
}
class BlogController extends Controller {
    public function getIndex($name) { echo "這是{$name}的博客列表"; }
    public function getShow($name, $blogId) { echo "{$name}的這篇博客的id為{$blogId}"; }
}

特點

  • **支援 Action 參數按順序綁定**(變數名無關,順序對應路由參數)。
  • 內建 route(), action(), url() 輔助函數產生 URL。
  • php artisan route:list 可視化檢視所有路由。

綜合比較表

框架路由定義風格參數綁定URL 產生巢狀路由學習曲線
ThinkPHP陣列正則對應按名稱/順序可選U() 函數平鋪正則模擬低
ZF2陣列樹狀結構手動提取$this->url()->fromRoute()原生子路由高
Yaf程式碼註冊 (Rewrite/Regex)按名稱綁定無內建(需自行拼裝)平鋪 Regex 模擬中
Laravel流暢介面 (Fluent)按順序綁定route()/action()/url()隱性巢狀(參數繼承)低

結語

各框架路由設計反映其核心哲學:ThinkPHP 重約定與簡潔、ZF2 重嚴謹結構與擴充性、Yaf 重效能與 C 擴展特性、Laravel 重開發體驗與表達力。選型時諜考量團隊熟悉度、專案規模與長期維護成本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved