前言
今天要來介紹的,是Laravel中的Controller,它做的事情就像先前提過的MVC中的Controller一樣,是用來處理網頁的要求邏輯。
在Laravel中,Controller可以將原先routes中要求處理邏輯加以分類組織,成為一個個獨立的class。
建立Controller
atisan中的make指令裡,也有著自動產生controller的指令
php artisan make:controller ProductController --resource --model=Product
指令結構是
php artisan make:controller {Controller Name} --{option 1} -- {option 2} ...
option有像是自動幫你產生好CRUD方法的 –resource
還有直接幫你連結好Model的 –model={Model Name}
Controller結構
<?php namespace App\Http\Controllers; // Controller的命名空間 use Illuminate\Http\Request; // 使用的類別 class PhotoController extends Controller { // 在這裡面撰寫你的方法 }
如果使用 –resource建立
它就會幫你建立好
index, create, store, show, ,edit, update, destroy 幾個方法
你可以在Controller其中自行建立方法,撰寫處理要求的邏輯
Route轉發要求給Controller
Controller的目的就是為了要處理要求
所以我們要在Route中定義要交哪個Controller的什麼方法來處理要求
讓我們看看常見的作法
// GET product的要求轉發給ProductController的index方法處理 Route::get('product', 'ProductController@index'); // GET product{id}的要求轉發給ProductController的show方法處理,同時會傳遞參數id Route::get('product/{id}', 'ProductController@show'); // POST product的要求轉發給ProductController的store方法處理 Route::post('product', 'ProductController@store');
另外,你可已透過下列的方式,轉發所有CRUD要求給指定的Controller
Route::resource('product', 'ProductController');
這一行會幫你處理7種不同的要求
Verb | URI | Action | Route Name |
---|---|---|---|
GET | /product |
index | product.index |
GET | /product/create |
create | product.create |
POST | /product |
store | product.store |
GET | /product/{photo} |
show | product.show |
GET | /product/{photo}/edit |
edit | product.edit |
PUT/PATCH | /product/{photo} |
update | product.update |
DELETE | /product/{photo} |
destroy | product.destroy |
如果有些資源要求處理你用不要,你可以使用only或是except的方式來篩選
Route::resource('product', 'ProductController', ['only' => [ 'index', 'show' ]]); Route::resource('product', 'ProductController', ['except' => [ 'create', 'store', 'update', 'destroy' ]]);
另外這邊稍微提一下偽造表單的方法
由於在HTML的Form中只有GET/POST,並沒有上面表格中的PUT, PATCH, DELETE,但Laravel需要去判別要求的種類
所以使用時需要在前端的HTML Form中加入
{{ method_field('PUT') }}
這樣的隱藏input field,這相當於
<input name="_method" type="hidden" value="PUT">
總結
今天的Controller的教學部分大概就到這邊,有點短XD,因為controller做的事情其實也很單純,重點在於controller的方法內容,而這部分之後會帶各位實作。
當然伴隨著controller的使用,可能還會用到repository, service的模式,不過那部份比較深入也比較複雜,我也只是初出茅廬的小嫩嫩,這個系列就不多加討論,以後有機會再跟各位分享。
今日所介紹的有
- Controller簡介
- 透過artisan make建立Controller
- 檢視Controller的結構
- Route與Controller
- 偽造表單方法
我們下次見,See ya!