Laravel 4 對象化"分組路由"協助工具輔助

來源:互聯網
上載者:User

標籤:des   http   java   使用   os   io   strong   檔案   

laravel-route-group

對象化分組路由協助工具輔助

使用前的準備

在 composer.json 檔案中申明依賴:

"five-say/laravel-route-group": "1.*"

在 /app/config/app.php 中設定“服務提供者”與“別名”

‘providers‘ => array(    ...    ‘FiveSay\LaravelRouteGroup\ServiceProvider‘,),‘aliases‘ => array(    ...    ‘RouteGroup‘ => ‘FiveSay\LaravelRouteGroup\Facade‘,),
使用方法
RouteGroup::make()->controller(‘UserController‘)->go(function ($route) {    $route->get(‘/‘)->uses(‘index‘);});

想知道它為我們註冊了什麼路由?我們來加一個小尾巴 ->dd() 就像下面這樣:

RouteGroup::make()->controller(‘UserController‘)->go(function ($route) {    $route->get(‘/‘)->uses(‘index‘);})->dd();

雖然對象化了,但總覺的代碼量反而更多了是不是?沒關係,讓我們來個霸氣點的:

RouteGroup::make(‘user‘)->asPrefix(‘user‘)->controller(‘UserController‘)->go(function ($route) {    $route->index()->create()->store()->show()->edit()->update()->destroy();})->dd();

現在有點感覺了?噢不,官方貌似也提供了一個方法 Route::resource(‘user‘, ‘UserController‘);!完敗?不,這裡可以做到更多:

RouteGroup::make(‘user‘)->asPrefix(‘user‘)->controller(‘UserController‘)    ->go(function ($route) {        $route            ->index(  )            ->create( )->before(‘allowCreate‘)            ->store(  )->before(‘allowCreate‘)            ->show(   )            ->edit(   )->before(‘allowEdit‘  )            ->update( )->before(‘allowEdit‘  )            ->destroy()->before(‘allowDelete‘);        # 禁用        $route->get(‘/{id}/ban‘  )->as(‘ban‘  )->uses(‘ban‘  )->before(‘auth‘)->has(‘ban‘);        # 解除禁用        $route->get(‘/{id}/unban‘)->as(‘unban‘)->uses(‘unban‘)->before(‘auth‘)->has(‘ban‘);    })->dd();

看看我們都完成了哪些路由的註冊:

注意 has() 需配合“路由許可權過濾器”使用:

Route::filter(‘hasAccess‘, function ($route, $request, $permission) {    if (! user()->hasAccess($permission)) {        App::abort(403);    }});

上例中的 user()->hasAccess($permission) 只是一個例子,作用是“擷取目前使用者執行個體,並判斷使用者是否有給定的操作許可權”,需根據實際情況自行調整。

哦,對了,這裡還有個大尾巴 ->ddAll() 它將輸出在此之前,由此輔助註冊的所有路由資訊:

RouteGroup::make(‘user‘)->asPrefix(‘user‘)->controller(‘UserController‘)    ->go(function ($route) {        ...    })->ddAll();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.