場景:模塊中有登錄及其他操作,未登錄用戶禁止訪問非登錄操作。在 _initialize 中判斷 Session,但登錄動作本身也會觸發 _initialize,導致死循環。
ThinkPHP 中可通過 ACTION_NAME 常量或 $this->actionName 獲取當前動作名,在 _initialize 中排除登錄相關動作。
public function _initialize() {
// 定義無需登錄的動作列表
$publicActions = ['login', 'verify', 'register', 'logout'];
if (in_array(ACTION_NAME, $publicActions)) {
return; // 直接返回,不做攔截
}
// 登錄驗證邏輯
if (!session('?user')) {
$this->error('請先登錄', U('login'));
}
}
class BaseController extends Controller {
protected $noAuthActions = [];
public function _initialize() {
if (!in_array(ACTION_NAME, $this->noAuthActions)) {
if (!session('?user')) $this->redirect('Public/login');
}
}
}
class UserController extends BaseController {
protected $noAuthActions = ['login', 'verify'];
// ...
}
ThinkPHP 官方討論:https://www.thinkphp.cn/topic/3244.html
核心原則:在入口處識別「公開動作」並放行,避免攔截器攔截自身登錄入口。