thinkphp5底层基类封装、内部类函数
记录下thinkphp5自定义底层基类、内部类函数使用笔记 大部分笔记来自tp手册。
底层常用代码的封装
在控制器中基类的起着至关重要的作用,整个项目的代码安全,复杂程度,易读性都要看你项目的基类架构的.
比如api中都需要某一个功能函数,我们就可以写在基类里。
贴上一个基类返回错误码的例子:
<?php namespace app\member\controller; class Base extends \app\base\controller\Base { static public function showReturnCode($code = '', $data = [], $msg = '') { $return_data = [ 'code' => '500', 'msg' => '未定义消息', 'data' => $code == 1001 ? $data : [], ]; if (empty($code)) return $return_data; $return_data['code'] = $code; if(!empty($msg)){ $return_data['msg'] = $msg; }else if (isset(ReturnCode::$return_code[$code]) ) { $return_data['msg'] = ReturnCode::$return_code[$code]; } return $return_data; } static public function showReturnCodeWithOutData($code = '', $msg = '') { return self::showReturnCode($code,[],$msg); } }
基类:
<?php namespace app\base\controller; class ReturnCode { static public $return_code = [ '1001' => '操作成功', '1002' => '你想做什么呢', //非法的请求方式 非ajax '1003' => '请求参数错误', //如参数不完整,类型不正确 '1004' => '请先登陆再访问', //未登录 或者 未授权 '1005' => '请求授权不符', ////非法的请求 无授权查看 '1006' => '数据加载失败', // '1010' => '数据不存在', // '1020' => '验证码输入不正确', // '1021' => '用户账号或密码错误', // '1022' => '用户账号被禁用', // '1030' => '数据操作失败', // ]; }
然后就可以调用了
private function getUid(){ //数据库字段 网页字段转换 $param = [ 'userid' => 'userid', 'userpwd' => 'userpwd', 'mobile' => 'mobile', ]; $param_data = $this->buildParam($param); if (empty($param_data['userid'])&&empty($param_data['mobile'])) return self::showReturnCodeWithOutData(1003); $check_login = $this->doModelAction($param_data, 'base/Member.login', 'base/Member', 'checkLogin'); if (!isset($check_login['code'])) $this->showReturnCodeWithSaveLog(1111); if ($check_login['code'] == 1001) { } return $check_login; }
框架构造函数使用
构造函数 在类的初始化时候执行的一个方法,构造函数中不要使用return关键词。
那么我们经常在构造函数里面做做什么呢?
- 数据初始化 注入对象等
- 前置工作的处理
- 权限判断
我们看一下TP5 控制器的构造函数,他在初始化时候注入了request对象,我们继承了控制器,直接就可以使用$this->request调用,同时也封装了View类.同时对前置的beforeActionList属性的方法 进行处理.
public function __construct(Request $request = null) { if (is_null($request)) { $request = Request::instance(); } $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); $this->request = $request; // 控制器初始化 $this->_initialize(); // 前置操作方法 if ($this->beforeActionList) { foreach ($this->beforeActionList as $method => $options) { is_numeric($method) ? $this->beforeAction($options) : $this->beforeAction($method, $options); } } }
对于权限判断的例子:
public function _initialize() { parent::_initialize(); // TODO: Change the autogenerated stub $user_agent = $this->request->server('HTTP_USER_AGENT'); if (! strpos($user_agent, 'MicroMessenger') === false ) $this->isWechatBrowser = true; //判断提交方式和是否微信浏览器 if ($this->request->method() == 'GET' && $this->isWechatBrowser === true){ //未登录 重新登录 if (!$this->checkAuth()&& !$this->no_login ) $this->wxoauth(); $this->isLogin=true; //设置全局登录 $this->loginGlobal(); if(!$this->isReg){ if(!$this->checkUuidMobile()) $this->redirect('user/user_blind.html'); } } }
控制起来继承:
<?php namespace app\api\controller; class WxpayAction extends Auth { public function _initialize() { config('default_return_type','html'); parent::_initialize(); // TODO: Change the autogenerated stub } public function index($order_no='2017020453102495'){ if(!$this->isWechatBrowser){ //******* 为了演示方便 这里省略了订单的是否支付验证 另外 微信支付本身就有支付重复验证 这里并没有加入乐观锁过滤 //******* $data=controller('base/WxPay')->payByOrderNo($order_no); $assign_data=[ 'title'=>'为了家健康--订单支付', 'amount'=>$data['amount'], 'order_no'=>$order_no, "jsApiParameters" =>$data['jsApiParameters'], 'openid'=>$this->open_id, 'data_md5'=>md5($order_no.$this->open_id.$data['amount']), //md5验证( 订单号 openid 金额) ]; $this->assign($assign_data); return $this->fetch('wxpay/index'); } public function showOrdersPayOk($order_no,$order_amount,$data_md5){ //md5验证( 订单号 openid 金额) if (md5($order_no.$this->open_id.$order_amount)<>$data_md5){ $assign_data=[ 'title'=>'为了家健康--支付出错了', 'content'=>'你要支付的订单号不存在请核对后再支付!', ]; $this->assign($assign_data); return $this->fetch('wxpay/err'); }else{ $assign_data=[ 'title'=>'为了家健康--该订单已经支付成功', 'amount'=>$order_amount, 'order_no'=>$order_no, ]; $this->assign($assign_data); return $this->fetch('wxpay/ok'); } } public function jsSign($url=''){ $url= $url ? : $this->request->server('HTTP_REFERER'); return json(controller('base/WxApi')->getJsSign($url)); }
框架析构函数使用
析构函数就是一个收尾的一个方法,
例子:创建一个虚拟基类
<?php namespace app\base\controller; use think\Cache; use think\Controller; use think\Session; use think\Loader; abstract class Base extends Controller { protected $error; //出错时候的记录 protected $log=[]; //要保存的记录 protected $saveLog = false ; static public function showReturnCode($code = '', $data = [], $msg = '') { $return_data = [ 'code' => '500', 'msg' => '未定义消息', 'data' => $code == 1001 ? $data : [], ]; if (empty($code)) return $return_data; $return_data['code'] = $code; if(!empty($msg)){ $return_data['msg'] = $msg; }else if (isset(ReturnCode::$return_code[$code]) ) { $return_data['msg'] = ReturnCode::$return_code[$code]; } return $return_data; } protected function addLog($code='',$msg=''){ $this->log[] =[ 'uuid' => $this->uuid, 'url' => $this->request->url(true), 'method' => $this->request->method(), 'data' => $this->getData(), 'ip' => $this->request->ip(), 'code'=>$code, 'desc' => $msg, ]; } protected function toSaveLog(){ $this->saveLog = true ; $this->addLog(); } protected function showReturnCodeWithSaveLog($code = '', $data = [], $msg = ''){ $this->saveLog = true ; $this->addLog($code,$msg); return self::showReturnCode($code, $data, $msg); } protected function getData(){ if ($this->request->isPost()){ return $this->request->post(); }else{ return $this->request->get(); } } protected function saveLogAction(){ if (!empty($this->log)){ foreach($this->log as $value){ dump($value); } } } public function __destruct() { // TODO: Implement __destruct() method. //记录日志 if (!empty($this->log) && $this->saveLog == true){ $this->saveLogAction(); } } }
控制器继承:
<?php namespace app\member\controller; use app\base\model\Member; use think\Cache; use think\Db; class Test extends Base { public function index(){ return $this->showReturnCodeWithSaveLog(1001,'演示析构函数成功了'); } }
thinkphp5底层基类封装、内部类函数的更多相关文章
- C++:抽象基类和纯虚函数的理解
转载地址:http://blog.csdn.net/acs713/article/details/7352440 抽象类是一种特殊的类,它是为了抽象和设计的目的为建立的,它处于继承层次结构的较上层. ...
- C++基础知识 基类指针、虚函数、多态性、纯虚函数、虚析构
一.基类指针.派生类指针 父类指针可以new一个子类对象 二.虚函数 有没有一个解决方法,使我们只定义一个对象指针,就可以调用父类,以及各个子类的同名函数? 有解决方案,这个对象指针必须是一个父类类型 ...
- 四、spring集成ibatis进行项目中dao层基类封装
Apache iBatis(现已迁至Google Code下发展,更名为MyBatis)是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库 ...
- salesforce 零基础学习(四十八)自定义列表分页之Pagination基类封装 ※※※
我们知道,salesforce中系统标准列表页面提供了相应的分页功能,如果要使用其分页功能,可以访问http://www.cnblogs.com/zero-zyq/p/5343287.html查看相关 ...
- Android 开发技巧 - Android 6.0 以上权限大坑和权限检查基类封装
简单介绍 关于运行时权限的说法,早在Google发布android 6.0的时候,大家也听得蛮多的.从用户的角度来讲,用户是受益方,更好的保护用户的意思,而对于开发者来说,无疑增加了工作量. 对于6. ...
- python基础(14)-反射&类的内置函数
反射 几个反射相关的函数可参考python基础(10)-匿名函数&内置函数中2.2.4反射相关 类的一些内置函数 __str__()&__repr__() 重写__str__()函数类 ...
- C++ 由虚基类 虚继承 虚函数 到 虚函数表
//虚基类:一个类可以在一个类族中既被用作虚基类,也被用作非虚基类. class Base1{ public: Base1(){cout<<"Construct Base1!&q ...
- (转)(C++)关于抽象基类和纯虚函数
★抽象类:一个类可以抽象出不同的对象来表达一个抽象的概念和通用的接口,这个类不能实例化(创造)对象. ★纯虚函数(pure virtual):在本类里不能有实现(描述功能),实现需要在子类中实现.例: ...
- python面向对象的多态-类相关内置函数-类内置魔法函数-迭代器协议-上下文管理-04
多态 一种事物具备不同的形态 例如:水 --> 固态.液态.气态 多态:# 多个不同对象可以相应同一个对象,产生不同的结果 首先强调,多态不是一种特殊的语法,而是一种状态,特性(多个不同对象可以 ...
随机推荐
- b161: NOIP2007 4.Hanoi双塔问题
zerojudge 汉诺塔?图片问度娘 b161: NOIP2007 4.Hanoi双塔问题 题目: 给定A.B.C三根足够长的细柱,在A柱上放有2n个中间有孔的圆盘,共有n个不同的尺寸,每个尺寸都 ...
- PLC与上位机的socket通讯——ABB机器人程序(三)
源程序:https://github.com/935094505/ABB-socket-communication 程序范例 觉得有帮助,别忘了打赏下
- Tempter of the Bone(DFS+剪枝)
Problem Description The doggie found a bone in an ancient maze, which fascinated him a lot. However, ...
- SpringBoot——Web开发(静态资源映射)
静态资源映射 SpringBoot对于SpringMVC的自动化配置都在WebMVCAutoConfiguration类中. 其中一个静态内部类WebMvcAutoConfigurationAdapt ...
- netCDF4 not installed properly - DLL load failed (netCDF4安装问题)
环境描述:windows10 ,conda,python3.6 问题描述:netCDF4是python中用来处理地球气象数据的文件读取包,在安装完成后,from netCDF4 import Data ...
- supervisor模块学习使用
supervisor组件 supervisord supervisord是supervisor的服务端程序. 启动supervisor程序自身,启动supervisor管理的子进程,响应来自clien ...
- 记一次java-selenium自动抢红包最简单案例1
案例网址:http://xinyue.qq.com/act/pc/xyjf/a20170907envelopes/index.htm?ADTAG=AD_gw.home.pt.2_dyghb.20170 ...
- 深度汉化GCompris-qt,免费的幼儿识字软件
1 需求 因为有个小孩上幼儿园了,想开始教他一些汉语拼音和基本的汉字,但通过一书本和卡片又有些枯燥乏味,于上就上网搜索一些辅助认字的应用,还购买了悟空识字APP,在用的过程中发现他设置了很严格的关卡, ...
- elasticsearch应用于产品列表
package com.linkwee.web.service; import java.util.List; import com.linkwee.api.request.cim.ProductPa ...
- 【系统设计】分布式唯一ID生成方案总结
目录 分布式系统中唯一ID生成方案 1. 唯一ID简介 2. 全局ID常见生成方案 2.1 UUID生成 2.2 数据库生成 2.3 Redis生成 2.4 利用zookeeper生成 2.5 雪花算 ...