因此,我無法找到我想要的確切解決方案,但我對此的處理方式可能有助於未來的其他人。
欲瞭解更多信息,我想這樣做的主要原因是,應用程序可以通過設置訪問ID(參考我的腳本$page
)確定用戶是否有權訪問該頁面。雖然我可以根據操作名稱設置訪問級別,但會根據不同的模塊,控制器等產生很多冗餘和衝突。
我如何去改變我的路由器,而不是直接調用操作,我將它設置爲通過執行函數調用該操作。
路由器
try {
$controller = new $controllerName;
$controller->execute($actionName);
}
catch (Exception $e) {
...
}
然後在我的baseController(這是由每個控制器擴展)我加的execute(),也是一個的checkAccess如果用戶有訪問,因爲這隻會返回true或false根據。這指的是另一個類(訪問)在訪問級別諮詢數據庫。
baseController
final public function execute($action) {
$actionMethod = '_action'.$action;
$accessMethod = '_access'.$action;
if (!method_exists($this, $actionMethod)) {
throw new Exception('Action method not defined.');
}
if (!method_exists($this, $accessMethod)) {
throw new Exception('Access method not defined.');
}
$page = $this->$accessMethod();
if (strtolower($page) != 'public' and !Access::check($page)) {
throw new Exception("Access denied for action $action.");
}
$this->$actionMethod();
}
final public function checkAccess($action) {
$actionMethod = '_action'.$action;
$accessMethod = '_access'.$action;
if (!method_exists($this, $actionMethod) or !method_exists($this, $accessMethod)) {
return false;
}
$page = $this->$accessMethod;
if (strtolower($page) == 'public' or Access::check($page)) {
return true;
}
else {
return false;
}
}
最後,現在我可以設置在控制器(動作/接入)兩種不同的保護方法。如果缺少任何一個,execute()會拋出相關異常並停止運行。
示例控制器
class Controller extends baseController {
protected function _accessTest() {
return 'access_page_id';
}
protected function _actionTest() {
...code here...
}
}
你可以做一個堆棧跟蹤,但它可能更容易做你在說什麼你不想做的事 - 把它包在一個方便的功能... ? –
是的,我想不出有什麼辦法可以解決這個問題,但是在每種方法中添加一個支票是沒有意義的,因爲對於我或者其他開發控制器的人來說,這應該是一種失敗保險,必須進行編碼,那麼它不是一個很大的故障安全。 – Devon