CI4框架應用六 - 控制器應用(轉載)
阿新 • • 發佈:2020-08-05
這節我們來分析一下控制器的應用,我們看到系統提供的控制器都是繼承自一個BaseController,我們來分析一下這個BaseController的作用
1 use CodeIgniter\Controller; 2 3 class BaseController extends Controller 4 { 5 6 /** 7 * An array of helpers to be loaded automatically upon 8 * class instantiation. These helpers will be available 9 * to all other controllers that extend BaseController. 10 * 11 * @var array 12 */ 13 protected $helpers = []; 14 15 /** 16 * Constructor. 17 */ 18 public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) 19 { 20 // Do Not Edit This Line 21 parent::initController($request, $response, $logger); 22 23 //-------------------------------------------------------------------- 24 // Preload any models, libraries, etc, here. 25 //-------------------------------------------------------------------- 26 // E.g.: 27 // $this->session = \Config\Services::session(); 28 } 29 }
這個控制器的意義就是一個載入元件的場所,把一些常用的元件轉成該類的屬性,那麼其它的控制器繼承了這個類也就獲得了這些屬性,可以在開發中直接使用了,或是預載入一些函式庫,在開發中可以直接使用這些函式庫裡的函式。
我們先來看一下initController這個方法,這個方法的說明是構造器,功能類似於構造方法,但這個只是一個普通的方法,是在類被例項化後手動呼叫的,這個方法接受三個引數,分別是:
1. $request 請求物件
2. $response 響應物件
3. $logger 日誌物件
在構造器方法執行後會轉成自身的屬性:
1. $this->request
2. $this->response
3. $this->logger
其中$this->request 特別重要,和使用者請求相關的所有資訊都可以從這個物件獲得
我們看到這個構造器方法還可以載入任何模型,庫等等, 例如:
1 /** 2 * Constructor. 3 */ 4 public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) 5 { 6 // Do Not Edit This Line 7 parent::initController($request, $response, $logger); 8 9 //-------------------------------------------------------------------- 10 // Preload any models, libraries, etc, here. 11 //-------------------------------------------------------------------- 12 // E.g.: 13 $this->session = \Config\Services::session(); // 載入session 14 $this->db = \Config\Database::connect(); // 載入db連線 15 }
這個BaseController還有一個屬性$helpers,是一個數組,可以將想要載入的函式庫的名字放在該陣列中,在類被例項化後,系統會遍歷這個陣列,依次載入對應的函式庫。