ThinkPHP 6.0 移除基础控制器及影响
近期将项目迁移至 ThinkPHP 6.0 版本,初期安装过程较为顺畅,但官方升级指南特别提示:
系统已取消提供基础控制器类 think\Controller,此前依赖的 success、error、redirect 及 result 等方法,现需在自定义的基础控制器中自行实现。
这表示开发者必须手动重构并实现原先的一系列便捷函数。
此处参考 ThinkPHP 5.1 的跳转源码逻辑进行优化改进,具体实施步骤如下:
首先,在 app 目录下新建 tpl 文件夹,并将 dispatch_jump.tpl 文件放入其中,该文件可直接从原 TP5 项目中复制获取。
其次,在 config 目录下的 app.php 配置文件中,添加模板文件的路径设置。
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => app()->getRootPath() . '/app/tpl/dispatch_jump.tpl',
'dispatch_error_tmpl' => app()->getRootPath() . '/app/tpl/dispatch_jump.tpl',
最后,在基类 BaseController 中添加以下核心代码以实现功能。
use think\exception\HttpResponseException;
use think\Response;
……
/**
* 操作成功跳转的快捷方法
* @access protected
* @param mixed $msg 提示信息
* @param string $url 跳转的URL地址
* @param mixed $data 返回的数据
* @param integer $wait 跳转等待时间
* @param array $header 发送的Header信息
* @return void
*/
protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
{
if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
$url = $_SERVER["HTTP_REFERER"];
} elseif ($url) {
$url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
}
$result = [
'code' => 1,
'msg' => $msg,
'data' => $data,
'url' => $url,
'wait' => $wait,
];
$type = $this->getResponseType();
// 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
if ('html' == strtolower($type)) {
$type = 'view';
}
$response = Response::create($result, $type)->header($header)->options(['jump_template' => app()->config->get('app.dispatch_success_tmpl')]);
throw new HttpResponseException($response);
}
/**
* 操作错误跳转的快捷方法
* @access protected
* @param mixed $msg 提示信息
* @param string $url 跳转的URL地址
* @param mixed $data 返回的数据
* @param integer $wait 跳转等待时间
* @param array $header 发送的Header信息
* @return void
*/
protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
{
if (is_null($url)) {
$url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
} elseif ($url) {
$url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
}
$result = [
'code' => 0,
'msg' => $msg,
'data' => $data,
'url' => $url,
'wait' => $wait,
];
$type = $this->getResponseType();
if ('html' == strtolower($type)) {
$type = 'view';
}
$response = Response::create($result, $type)->header($header)->options(['jump_template' => app()->config->get('app.dispatch_success_tmpl')]);
throw new HttpResponseException($response);
}
总结
以上内容介绍了基于 ThinkPHP 6.0 环境实现 success 和 error 跳转的方法,希望能对大家有所帮助。如有任何疑问,欢迎留言交流,小编会及时回复。感谢大家对本站的支持!若觉得本文有用,欢迎转载并注明出处。