yunzer/app/index/controller/BaseController.php
2025-05-19 22:24:30 +08:00

147 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare (strict_types = 1);
namespace app\index\controller;
use think\App;
use think\facade\View;
use think\facade\Request;
use think\facade\Db;
use app\service\VisitStatsService;
/**
* 前台控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
protected $visitStats;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
$this->visitStats = new VisitStatsService();
// 控制器初始化
$this->initialize();
}
/**
* 初始化
*/
protected function initialize()
{
// 记录访问
$this->visitStats->recordVisit($this->getControllerName());
// 获取配置
$configList = Db::table('yz_admin_config')
->where('config_status', 1)
->order('config_sort DESC')
->select()
->toArray();
// 将配置数据转换为键值对形式
$config = [];
foreach ($configList as $item) {
$config[$item['config_name']] = $item['config_value'];
}
// 设置通用变量
View::assign([
'config' => $config
]);
}
/**
* 获取控制器名称移除Controller后缀
* @return string
*/
public function getControllerName()
{
$className = get_class($this);
$className = substr($className, strrpos($className, '\\') + 1);
return str_replace('Controller', '', $className);
}
/**
* 渲染模板输出
* @param string $template 模板文件
* @param array $vars 模板变量
* @return string
*/
protected function fetch($template = '', $vars = [])
{
return View::fetch($template, $vars);
}
/**
* 操作成功跳转
* @param string $msg 提示信息
* @param string $url 跳转地址
* @param mixed $data 返回数据
* @param integer $wait 跳转等待时间
* @return void
*/
protected function success($msg = '', $url = null, $data = '', $wait = 3)
{
if (Request::isAjax()) {
return json([
'code' => 1,
'msg' => $msg,
'data' => $data,
'url' => $url
]);
}
return View::fetch('common/success', [
'msg' => $msg,
'url' => $url,
'data' => $data,
'wait' => $wait
]);
}
/**
* 操作失败跳转
* @param string $msg 提示信息
* @param string $url 跳转地址
* @param mixed $data 返回数据
* @param integer $wait 跳转等待时间
* @return void
*/
protected function error($msg = '', $url = null, $data = '', $wait = 3)
{
if (Request::isAjax()) {
return json([
'code' => 0,
'msg' => $msg,
'data' => $data,
'url' => $url
]);
}
return View::fetch('common/error', [
'msg' => $msg,
'url' => $url,
'data' => $data,
'wait' => $wait
]);
}
}