thinkphp5封装CURD

浏览:4220 发布日期:2017/08/15 分类:系统代码 关键字: thinkphp5,封装代码,快捷代码
厌烦了每次写CURD的时候都给多次使用相同代码,虽然thinkphp的数据库查询修改之类还是比较简单的,但是为了解决代码耦合问题,能够快速更换框架。有这种需求的可以看一看.
最近加我QQ的有点多,问题回复不过来,新建了一个QQ群,如果想加可以加一下。


使用代码:<?php
    
    namespace app\pc\controller;
    
    use think\Db;
    
    class Index extends Common
    {
        
        public function index()
        {
            $db_customer  = 'customer';
            $where['uid'] = '1';
            $field        = 'uid,name';
            $order        = 'uid desc';
            $limit        = 10;
            $insert_data  = ['name' => 'userName', 'pwd' => '123456'];
            $select       = $this->select($db_customer, $field, $where, $order, $limit);//查询多条
            $find         = $this->find($db_customer, $field);//查询单条
            $insert       = $this->insert($db_customer, $insert_data);//添加
            $delete       = $this->delete($db_customer, $where);
        }
    }
在controller文件夹内建立一个Common.php文件便于继承使用<?php
    /**
     * @author: 周洪亮
     * @copyright: 2017/7/2015:23
     */
    
    namespace app\pc\controller;
    
    use think\Config;
    use think\Controller;
    use think\Db;
    use think\View;
    
    class Common extends Controller
    {
        protected $view;
        
        // 架构方法注入
        public function _initialize()
        {
            $this->view = View::instance([], Config::get('view_replace_str'));
        }
        
        /**
         * @author:周洪亮<white_zhl@163.com>;
         * @copyright:2017/8/15;
         * @var:查询
         */
        public function select($db, $field = '', $where = '', $order = '', $limit = 5)
        {
            $data = Db::name($db)->field($field)->where($where)-          >order($order)->limit($limit)->select();
            
            return $data;
        }
        
        /**
         * @author:周洪亮<white_zhl@163.com>;
         * @copyright:2017/8/15;
         * @var:添加数据
         */
        public function insert($db, $data)
        {
            Db::name($db)->insert($data);
            $data = Db::name($db)->insertGetId($data);
            
            return $data;
        }
        
        /**
         * @author:周洪亮<white_zhl@163.com>;
         * @copyright:2017/8/15;
         * @var:查询单条数据
         */
        public function find($db, $field = '')
        {
            $data = Db::name($db)->field($field)->find();
            
            return $data;
        }
        
        public function delete($db, $where)
        {
            $data = Db::name($db)->where($where)->delete();
            
            return $data;
        }
    }
更多实例请访问我的个人博客:zhouhongliang.cn
评论( 相关
后面还有条评论,点击查看>>