Laravel學習總結二:基礎內容(Controller)

Laravel學習總結二:基礎內容(Controller)

2015/1/4 更新,修改即更新,也歡迎大家批評指正。一起學習,廣交編碼同仁。

控制器:

Laravel爲典型的MVC架構,其中的C角色就由控制器扮演,用來處理項目中的邏輯、處理判斷的功能。

爲了保持代碼的低耦合和高複用,我們在寫路由的控制操作的時候,一律不使用閉包,全部通過控制器來實現。


定義控制器

控制器類必須繼承BaseController類,如下代碼爲Laravel自帶的一個HomeController

<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function showWelcome()
	{
		return View::make('hello');
	}

}
該控制器用來返回一個名爲‘hello’ 的View視圖,這裏簡單說下請求的處理思路:請求到路由時,由路由進行判斷進行何種過濾操作,再進行何種控制器中的邏輯處理,處理完了之後,再返回一個response,該response一般就爲一個View視圖。

在控制器中定義過濾器

但是個人覺得這樣的功能沒啥用,在filter完全可以在Route進行關聯。所以這裏我不推薦

只要知道能這麼做就可以了

三種方式:

1在控制器類中的構造方法中

__construct()中指定過濾器

 public function __construct()
    {
        $this->beforeFilter('auth', array('except' => 'getLogin'));

        $this->beforeFilter('csrf', array('on' => 'post'));

        $this->afterFilter('log', array('only' =>
                            array('fooAction', 'barAction')));
    }

$this->beforefilter('auth',['except'=>'getlogin']);

2.在構造方法中,定義閉包函數來定義過濾方式

 public function __construct()
    {
        $this->beforeFilter(function()
        {
            //
        });
    }

3.在構造方式中,指定該控制器類中的其他方法來進行過濾操作

 public function __construct()
    {
        $this->beforeFilter('@filterRequests');
    }

    /**
     * Filter the incoming requests.
     */
    public function filterRequests($route, $request)
    {
        //
    }


隱式控制器

我本人並沒有使用過該方式,只是將學習的東西記錄下來
Route::controller('users', 'UserController');
該路由直接與UserController控制器類進行綁定,

首先

該Route::controller中有兩個參數:

1.爲URL中的基底
2.爲控制器的類

其次:

Next, just add methods to your controller, prefixed with the HTTP verb they respond to:
(官方文檔copy     https://laravel.com/docs/4.2/controllers#restful-resource-controllers)
需要在該控制器類中創建方法,方法名爲(前綴+資源),前綴爲請求的action方式 such as   GET  POST 
class UserController extends BaseController {

    public function getIndex()
    {
        //該方法是直接返回response
    }

    public function postProfile()
    {
        //使用post 該users/profile的url時,調用該方法來進行處理
    }

    public function anyLogin()
    {
        // 任何方式get/post 獲取該users/login 的URL時,該方法進行處理
    }
    public function getAdminProfile() 
    {
        //該方法對應的URL爲    users/admin-profile
    }
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章