### 使用控制器基類
系統內置了一個控制器基類`think\Controller`,本講內容就是來講解下這個控制器基類的功能和用法。
要使用控制器基類的功能,有兩種方式:繼承`think\Controller`基類和使用`Trait`引入`traits\controller\Jump`,繼承可以使用基類的完整功能,`Trait`引入的話只有部分功能,后面我們會提到。
#### 控制器初始化
如果控制器下面的每個操作都需要執行一些公共的操作(例如,權限和登錄檢查),有兩種方法,如果你沒有繼承系統的控制器基類,可以使用架構方法來進行初始化,例如:
~~~
<?php
namespace app\index\controller;
class Index
{
// 架構方法
public function __construct()
{
echo 'init<br/>';
}
public function hello()
{
return 'hello,world';
}
public function test()
{
return 'test';
}
}
~~~
如果已經繼承了系統控制器基類,那么可以使用控制器初始化方法:
~~~
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
// 初始化
protected function _initialize()
{
echo 'init<br/>';
}
public function hello()
{
return 'hello,world';
}
public function test()
{
return 'test';
}
}
~~~
無論使用何種方式,當我們訪問下面的URL地址:`http://tp5.com/index/index/hello`頁面輸出結果為:
> init
> hello,world
而當訪問:`http://tp5.com/index/index/test`頁面輸出結果為:
>
> init
> test
如果應用的所有控制器都需要執行一些公共操作,則只需要讓應用控制器都統一繼承一個公共的控制器類,然后在該公共控制器類里面定義初始化方法即可。
例如,在公共Base控制器類里面定義初始化方法:
~~~
<?php
namespace app\index\controller;
use think\Controller;
class Base extends Controller
{
// 初始化
protected function _initialize()
{
echo 'init<br/>';
}
}
~~~
然后其它控制器都繼承Base控制器類:
~~~
<?php
namespace app\index\controller;
use app\index\controller\Base;
class Index extends Base
{
public function hello()
{
return 'hello,world';
}
public function test()
{
return 'test';
}
}
~~~
> 初始化方法里面的return操作是無效的,也不能使用redirect助手函數進行重定向,如果你是要進行重定向操作(例如權限檢查后的跳轉)請使用$this->redirect()方法,參考后面的跳轉和重定向內容。不過,初始化方法中仍然支持拋出異常。