Phalcon 中控制器統(tǒng)一以 Controller 結(jié)尾,方法以 Action 結(jié)尾,如:TestController::indexAction,所有控制器都應(yīng)該繼承自Phalcon\Mvc\Controller。
初始化控制器
Phalcon\Mvc\Controller 提供了初始化函數(shù) initialize,它會(huì)最先執(zhí)行,官方不推薦使用 __construct(源碼中 __construct 定義了 final 屬性)。 initialize 僅會(huì)在事件 beforeExecuteRoute 成功執(zhí)行后被調(diào)用。
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function initalize()
{
// do something first ...
}
}
查看 Phalcon\Mvc\Controller 類源碼會(huì)發(fā)現(xiàn),也可以實(shí)現(xiàn) onConstruct 函數(shù)來使控制器對(duì)象創(chuàng)建后執(zhí)行一些初始化邏輯。
<?php
/**
* Phalcon\Mvc\Controller 類
*/
abstract class Controller extends Injectable implements ControllerInterface
{
/**
* Phalcon\Mvc\Controller constructor
*/
public final function __construct()
{
if method_exists(this, "onConstruct") {
this->{"onConstruct"}();
}
}
}
通過 onConstruct 函數(shù)實(shí)現(xiàn)初始化控制器:
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function onConstruct()
{
// do something first ...
}
}
獲取參數(shù)
URL 路由中的參數(shù)可以通過方法中直接傳入獲?。?/p>
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function indexAction($param1, $param2 = 'default value')
{
}
}
通過派遣器 Dispatcher 獲取參數(shù):
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function indexAction()
{
$param1 = $this->dispatcher->getParam('param1'); // 獲取參數(shù)param1
$param2 = $this->dispatcher->getParam('param2'); // 獲取參數(shù)param2
}
}
通過請(qǐng)求 Request 對(duì)象獲取參數(shù):
<?php
use Phalcon\Mvc\Controller;
classs TestController extends Controller
{
public function indexAction()
{
$name= $this->request->getPost('name'); // 獲取post參數(shù)name
$age = $this->request->getQuery('age'); // 獲取get參數(shù)age
}
}
在控制器中使用 DI 中注入的服務(wù)
Phalcon\Mvc\Controller 繼承的 injectable 類中封裝了獲取 DI 的方法,所有在控制器中可以方便的獲取 DI 中注入的各種服務(wù)。
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function indexAction()
{
$this->getDI()->get('service name');
$this->di->get('service name'); // 或者
}
}
綁定事件
控制器會(huì)自動(dòng)作為 dispatcher 事件的偵聽者,使用這些事件并實(shí)現(xiàn)這些方法后,便可以實(shí)現(xiàn)對(duì)應(yīng)被執(zhí)行的 action 的 before/after 鉤子函數(shù)。
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function beforeExecuteRoute($dispatcher)
{
// 在所有action之前執(zhí)行
if ($dispatcher->getActionName() == 'save') {
// do something before save action ...
}
}
public function afterExecuteRoute($dispatcher)
{
// 找到的action之后執(zhí)行
}
}
請(qǐng)求與響應(yīng)
在控制器中可以直接獲取請(qǐng)求和響應(yīng)對(duì)象:
<?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function indexAction()
{
$request = $this->request; // 獲取請(qǐng)求對(duì)象
$params = $request->getPost(); // 獲取post提交參數(shù)
$response = $this->response; // 獲取響應(yīng)對(duì)象
$response->setJsonContent(['a' => 11111, 'b' => 2222])->send(); // 輸出json字符串
}
}