这是关于WeEngine的第一篇文章。欲善其事,先利其器,这篇文章先不做源码分析,而是先把一些辅助的结构建立起来。
一,日志系统
data/config.php
$config['setting']['development'] = 1;
有了日志之后,调试将会事半功倍。打印日志的方法:
source/modules/engine.php
public static function logging($level = 'info', $message = '')
其中level可以是任意字符串。推荐使用error,warn,info,trace几个字符表示不同级别。例如:
WeUtility::logging('warn', 'Request Failed');
日志输出样例:
2014-04-03 19:57:30 trace :
------------
Array:
from : otP7TjgEgLrOKzp9TGuMx6x;
to : gh_765067e402 ;
time : 1396526250 ;
type : CLICK ;
event : CLICK ;
tousername : gh_765067e402 ;
fromusername : otP7TjgEgLrOKzp9TGuMx6x ;
createtime : 1396526250 ;
msgtype : event ;
eventkey : huodongzhaoji ;
2014-04-03 19:57:30 params :
------------
Array:
module : default ;
rule : -1 ;
2014-04-03 19:57:30 response :
------------
Array:
FromUserName : gh_765067e402 ;
ToUserName : otP7TjgEgLrOKzp9TGuMx6x ;
MsgType : news ;
ArticleCount : 2 ;
Articles : Array ;
调试时,可以用下面的命令持续观察日志最新输出:
tailf data/logs/xxxxxxx.log
二,全局变量
source/bootstarp.api.inc.php
global $_W;
此乃WeEngine精华所在。下面分述各个字段。
$_W['account']
$sql = "SELECT * FROM " . tablename('wechats') . " WHERE `hash`=:hash LIMIT 1";
$_W['account'] = pdo_fetch($sql, array(':hash' => $_GPC['hash']));
$_W['account']['default_message'] = iunserializer($_W['account']['default_message']);
$_W['account']['access_token'] = iunserializer($_W['account']['access_token']);
$_W['account']['payment'] = iunserializer($_W['account']['payment']);
wechats表记录的是公众账号信息,如下图所示。WeEngine比较强大的地方之一是可以管理多个公众号。
每个公众号都有一个唯一标示id:weid。下例中只存了一个公众号,weid编号为1.
从上面的代码中可知$_W['account']中保存了公众号的所有信息。其中default_message、access_token、payment三个参数是以 序列化的方式存入到wechats表中,所以读出的时候需要反序列化一下。
对于微信和易信分别使用了不同的序列化类,见source/class/weixin.account.class.php fetch_token():
if (empty($this->account['key']) || empty($this->account['secret'])) {
message('请填写公众号的appid及appsecret, (需要你的号码为微信服务号)!', create_url('account/post', array('id' => $this->account['weid'])), 'error');
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->account['key']}&secret={$this->account['secret']}";
$content = ihttp_get($url);
if(is_error($content)) {
message('获取微信公众号授权失败, 请稍后重试!错误详情: ' . $content['message']);
}
$token = @json_decode($content['content'], true);
if(empty($token) || !is_array($token) || empty($token['access_token']) || empty($token['expires_in'])) {
message('获取微信公众号授权失败, 请稍后重试! 公众平台返回原始数据为: <br />' . $content['meta']);
}
$record = array();
$record['token'] = $token['access_token'];
$record['expire'] = TIMESTAMP + $token['expires_in'];
$row = array();
// 序列化token,并更新到数据库中
$row['access_token'] = iserializer($record);
pdo_update('wechats', $row, array('weid' => $this->account['weid']));
return $record['token'];
还有几个变量很重要,源码中会经常遇到,用到的时候再详细介绍。
$_W['account']['modules'] = array();
$_W['setting'] = (array)cache_load("setting");
$_W['config']
We7官方关于全局变量有更详细的描述,
详见这里。