在代碼中埋入鉤子,然后執(zhí)行到埋點時,會調(diào)用鉤子方法,獲得結(jié)果。
而使用者可以花式實現(xiàn)鉤子,這樣代碼靈活性很高。
下面是cmf如何自定義后臺登陸界面的鉤子使用實例
配置說明配置
文件在 vendor/thinkcmf/src/App.php 294行左右引入12行,會判斷app目錄下是否有tags.php文件,有則引入配置文件
$module = $module ? $module . DIRECTORY_SEPARATOR : '';
$path = $this->appPath . $module;
if (empty($module) || empty(static::$modulesInited[$module])) {
// 加載初始化文件
if (is_file($path . 'init.php')) {
include $path . 'init.php';
} elseif (is_file($this->runtimePath . $module . 'init.php')) {
include $this->runtimePath . $module . 'init.php';
} else {
// 加載行為擴展文件
if (is_file($path . 'tags.php')) {
$tags = include $path . 'tags.php';
if (is_array($tags)) {
$this->hook->import($tags);
}
}
配置文件如下
return [
'admin_login' => [
'app\\portal\\behavior\\AdminLoginBehavior',
],
];
指定鉤子執(zhí)行的方法(數(shù)組類型)。鉤子可以有多個執(zhí)行方法,按照數(shù)組中順序執(zhí)行
實現(xiàn)鉤子
class AdminLoginBehavior
{
protected static $run = false;
// 行為擴展的執(zhí)行入口必須是run
public function run()
{
if (self::$run) {
return;
}
self::$run = true;
$view = View::instance();
$view->assign('site_info', cmf_get_option('site_info'));
return $view->fetch(":login");
}
}
入口函數(shù)為run方法,其他無特殊要求
其他說明
上面是自定義后臺登陸頁面的鉤子實現(xiàn)
埋點代碼在vendor/thinkcmf/cmf-app/src/admin/controller/PublicController.php 38行左右下面第6行。即為鉤子埋點
$admin_id = session('ADMIN_ID');
if (!empty($admin_id)) {//已經(jīng)登錄
return redirect(url("admin/Index/index"));
} else {
session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true);
$result = hook_one('admin_login');
if (!empty($result)) {
return $result;
}
return $this->fetch(":login");
}
cmf鉤子文檔
https://www.kancloud.cn/thinkcmf/doc5_1/963034
cmf后臺有很多鉤子,按照返回值定義,返回指定的返回值類型即可