不灭的焱

革命尚未成功,同志仍须努力

作者:php-note.com  发布于:2018-01-21 22:55  分类:PHP库/系统/微信  编辑

ThinkPHP模型  、CI查询构造器 类 / 表单验证类  (类库参考) 、sqlHelper

CI框架获取 控制器名 和 方法名

$con  = $this->router->fetch_class();   // 获取控制器名  
$func = $this->router->fetch_method();  // 获取方法名   

 

加载配置文件 config, 配置类 使用手册

$this->load->config('constants'); // 加载文件 config/constants.php  
$key_match = $this->config->item('operate_device_cmd');

$this->load->config('my');

 

$this->config->load('common/config_holiday', TRUE);  // 统一返回状态码loading
$holiday = $this->config->item('holiday', 'common/config_holiday');  // 法定节假日
$workday = $this->config->item('weekenworkday', 'common/config_holiday');  // 补假日

 

class Message extends BaseController{
    /**
     * 微信公众号 回调处理
     */
    public function index() {
        $CI = &get_instance();
        $CI->load->model('m_wechat_apps');
        $CI->load->model('m_wechat_fans');
                   
        $CI->load->config(ENVIRONMENT . '/config_wechat');
        $wechat_driver = $this->config->item('wechat_driver');

        $options = [
            'appid'          => $wechat_driver['appId'],            // 填写高级调用功能的appid
            'appsecret'      => $wechat_driver['appSecret'],        // 填写高级调用功能的密钥
            'encodingaeskey' => $wechat_driver['encodingaeskey'],   // 填写加密用的EncodingAESKey
            'token'          => $wechat_driver['token'],            // 填写你设定的key
        ];
      
        $CI->load->library('wx/CI_Wechat', $options);
        $CI->ci_wechat->valid();
        $type = $CI->ci_wechat->getRev()->getRevType();
     
        switch ($type) {
            case Wechat::MSGTYPE_TEXT:
                // 自动回复对话
                //$CI->ci_wechat->text("欢迎来到 xxx 公众号")->reply();
                exit;
                break;
            case Wechat::MSGTYPE_EVENT:
                $eventInfo = $CI->ci_wechat->getRevEvent();
                $event = isset($eventInfo['event']) ? $eventInfo['event'] : '';
                
                switch ($event) {
                    case Wechat::EVENT_SUBSCRIBE;       // 关注
                        $original_id = $CI->ci_wechat->getRevTo();
                        $open_id     = $CI->ci_wechat->getRevFrom();
                        
                        // 微信粉丝信息
                        $fans_info = $CI->ci_wechat->getUserInfo($open_id);
                        $unionid = isset($fans_info['unionid']) ? $fans_info['unionid'] : '';
                        
                        $fans = [
                            'app_id'         => $options['appid'],
                            'original_id'    => $original_id,
                            'open_id'        => $open_id,
                            'union_id'       => $unionid,
                            'is_subscribe'   => 1,
                            'subscribe_time' => date('Y-m-d H:i:s'),
                        ];
                        $CI->m_wechat_fans->save_fans($fans);
                        
                        break;
                    case Wechat::EVENT_UNSUBSCRIBE;     // 取消关注
                        $original_id = $CI->ci_wechat->getRevTo();
                        $open_id     = $CI->ci_wechat->getRevFrom();
                        $fans        = [
                            'app_id'           => $options['appid'],
                            'original_id'      => $original_id,
                            'open_id'          => $open_id,
                            'is_subscribe'     => 0,
                            'unsubscribe_time' => date('Y-m-d H:i:s'),
                        ];
                        $CI->m_wechat_fans->save_fans($fans);

                        break;
                }
                
                break;
            case Wechat::MSGTYPE_IMAGE:
                break;
            default:
                //$CI->ci_wechat->text("欢迎来到 xxx 公众号(2)")->reply();
        }
    }
} 

 

加载助手 helper

$this->load->helper('time');  // 加载文件 helpers/time_helper.php

 

加载模型 model

$this->load->model('M_car_device_info'); // 加载文件 models/M_car_device_info.php
$device_info = $this->M_car_device_info->get_record('xxx'); 

// 输出 SQL
echo $this->m_car_device_position->db->last_query();

 

加载视图 view

$this->load->view('Hardware_upgrade/software_list', $data, false); // 加载文件 views/Hardware_upgrade/software_list.php

 

加载服务 service

$this->load->service('S_device_ctrl'); // 加载文件 models/M_car_device_info.php
$this->S_device_ctrl->send_data_to_device();

 

加载其他类库 library

$this->load->library('log/Logger'); // 加载文件 libraries/log/Logger.php
$this->load->library('map/Baidu_map_api');

 

自定义 library 文件中, 引入 其他 类文件

// 日志
$CI = &get_instance();
$CI->load->library('log/Logger');
$CI->Logger->logs_debug("百度地图, 经纬度转换失败: " . $coords . "
", 'device_notify');

// 缓存
$CI = &get_instance();

// 设置
$CI->load->library('cache/Redis_handler');
$CI->redis_handler->set($cache_key, $value);
$CI->redis_handler->expire($cache_key, $cache_time);

// 获取
$CI->redis_handler->get($cache_key);

参考:http://codeigniter.org.cn/user_guide/general/creating_libraries.html

 

缓存 cache

// 缓存 Redis (在 System 中)
libraries/Cache/drivers/Cache_redis.php

// 待发送数据
$send_data = array(
   'device_no'       => $device_info['device_no'], // 设备号
   'opera_cmd'       => $operate_type[$param['operate_type']], // 操作命令
   'access_ip'       => $device_info['access_ip'],
   'access_port'     => $device_info['access_port'],
   'fd'              => $device_info['fd'],
);

// 放到 redis 队列 中去 (用 redis 扩展的原生方法)
$this->load->driver('Cache'); // 加载文件  libraries/Cache/drivers/Cache_redis.php
$result = $this->cache->redis->get_instance()->rpush('client_pending_package', json_encode($send_data));

 

打印SQL

echo $this->db->last_query();

 

 

生成查询结果

1、$this->db->result_array() :返回 多维数组 (多条)记录

2、$this->db->row_array():返回 一维数组(单条)记录

参考:http://codeigniter.org.cn/user_guide/database/results.html

 

 

分页

// 查询分页总数
$this->db->count_all_results('my_table', FALSE);

// 渲染参考:

SELECT COUNT(*) AS `numrows`
FROM `ltb_line`
WHERE `parent_line_id` =0
AND `flag` = 1

 

// Produces: LIMIT 20, 10 (in MySQL.  Other databases have slightly different syntax)
$this->db->limit(10, 20);

 

public function delete_line() {
	$this->load->service('s_line');
	$url = '/tool/delete_line';
	
	// 获取记录
	$fields = 'ltb_line_id,line_start_time,time_range';
	$where = array(
		'parent_line_id' => 0,
		'flag'           => 1
	);
	
	// 总记录数
	$count = $this->db
		->select($fields)
		->from('ltb_line')
		->where($where)
		->count_all_results(null, FALSE);
	
	// 分页情况
	$page_size  = 10; // 每页记录数
	$page_index = intval($_GET['page']);
	$page_count = ceil($count / $page_size);
	$page_index = max(1, $page_index);
	$page_index = min($page_index, $page_count); 
    $offset     = $page_size * ($page_index - 1);
	
	if (intval($_GET['page']) > $page_count) {
		echo "已完成";
		die();
	}
	
	// 分页记录
	$list = $this->db->limit($page_size, $offset)->get()->result_array();
 
	echo "正在处理<span style='color:red'> {$page_index} / {$page_count} 页";
	
	// 处理当前分页数据
	foreach ($list as $_parent_line) {
		$this->s_line->check_child_line_time($_parent_line['ltb_line_id']);
	}
	
	// 页面跳转
	$page_index++;
	http_goto($url . '?page=' . $page_index, 1);
}

 

/**
 * URL跳转
 *
 * @param string $url  跳转地址
 * @param int    $time 跳转延时(单位:秒)
 * @param string $msg  提示语
 */
function http_goto($url = 'http://php-note.com', $time = 0, $msg = '') {
    //if (empty($msg)) {
    //    $msg = "系统将在 {$time}秒 之后自动跳转到 {$url} !";
    //}

    if (headers_sent()) {
        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0) {
            $str .= $msg;
        }
        die($str);
    } else {
        if ($time === 0) {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: " . $url);
        } else {
            header("Content-type: text/html; charset=utf-8");
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        die();
    }
}