分享淘宝API辅助函数-适用CI框架
最近在重写一个淘宝客的网站,考虑到以后的拓展性,所以把它整合进CI里面了,这就出现个问题了,淘宝的SDK怎么整合进类库呢?仔细阅读淘宝API文档后,发现一个非SDK调用方法,我在这基础上加以修改整合成CI的helper函数,现在把源码分享给大家,希望帮到有需要的同学。
调用方法很简单,传入一个数组参数,其中method是你打算调用的API接口,其余的参数根据API接口的实际需要填入。我这里给个调用例子给大家看下。
代码如下 | 复制代码 |
|
memche消息队列的原理就是在key上做文章,用以做一个连续的数字加上前缀记录序列化以后消息或者日志。然后通过定时程序将内容落地到文件或者数据库。
php实现消息队列的用处比如在做发送邮件时发送大量邮件很费时间的问题,那么可以采取队列。
方便实现队列的轻量级队列服务器是:
starling支持memcache协议的轻量级持久化服务器
https://github.com/starling/starling
Beanstalkd轻量、高效,支持持久化,每秒可处理3000左右的队列
http://kr.github.com/beanstalkd/
php中也可以使用memcache/memcached来实现消息队列。
代码如下 | 复制代码 |
<?php class QMC { /** /** |
基于PHP共享内存实现的消息队列:
代码如下 | 复制代码 |
<?php private $front = 0; // 队头指针 private $blockSize = 256; // 块的大小(byte) private $filePtr = './shmq.ptr'; private $semId = 0; $this->shmId = shmop_open($shmkey, "c", 0644, $this->memSize ); // 申?一个信号量 $this->init(); private function init() public function getLength() public function enQueue( $value ) $data = $this->encode($value); public function deQueue() private function ptrInc( $ptr ) private function encode( $value ) echo strlen($data); echo $this->blockSize -1; if ( strlen($data) > $this->blockSize -1 ){ private function decode( $value ) public function __destruct() sem_release($this->semId); // 出临界区, 释放信号量 /* |
对于一个很大的消息队列,频繁进行进行大数据库的序列化 和 反序列化,有太耗费。下面是我用PHP 实现的一个消息队列,只需要在尾部插入一个数据,就操作尾部,不用操作整个消息队列进行读取,与操作。但是,这个消息队列不是线程安全的,我只是尽量的避免了冲突的可能性。如果消息不是非常的密集,比如几秒钟才一个,还是可以考虑这样使用的。
如果你要实现线程安全的,一个建议是通过文件进行锁定,然后进行操作。下面是代码:
代码如下:
代码如下 | 复制代码 |
class Memcache_Queue { private $memcache; private $name; private $prefix; function __construct($maxSize, $name, $memcache, $prefix = "__memcache_queue__") { if ($memcache == null) { throw new Exception("memcache object is null, new the object first."); } $this->memcache = $memcache; $this->name = $name; $this->prefix = $prefix; $this->maxSize = $maxSize; $this->front = 0; $this->real = 0; $this->size = 0; } function __get($name) { return $this->get($name); } function __set($name, $value) { $this->add($name, $value); return $this; } function isEmpty() { return $this->size == 0; } function isFull() { return $this->size == $this->maxSize; } function enQueue($data) { if ($this->isFull()) { throw new Exception("Queue is Full"); } $this->increment("size"); $this->set($this->real, $data); $this->set("real", ($this->real + 1) % $this->maxSize); return $this; } function deQueue() { if ($this->isEmpty()) { throw new Exception("Queue is Empty"); } $this->decrement("size"); $this->delete($this->front); $this->set("front", ($this->front + 1) % $this->maxSize); return $this; } function getTop() { return $this->get($this->front); } function getAll() { return $this->getPage(); } function getPage($offset = 0, $limit = 0) { if ($this->isEmpty() || $this->size < $offset) { return null; } $keys[] = $this->getKeyByPos(($this->front + $offset) % $this->maxSize); $num = 1; for ($pos = ($this->front + $offset + 1) % $this->maxSize; $pos != $this->real; $pos = ($pos + 1) % $this->maxSize) { $keys[] = $this->getKeyByPos($pos); $num++; if ($limit > 0 && $limit == $num) { break; } } return array_values($this->memcache->get($keys)); } function makeEmpty() { $keys = $this->getAllKeys(); foreach ($keys as $value) { $this->delete($value); } $this->delete("real"); $this->delete("front"); $this->delete("size"); $this->delete("maxSize"); } private function getAllKeys() { if ($this->isEmpty()) { return array(); } $keys[] = $this->getKeyByPos($this->front); for ($pos = ($this->front + 1) % $this->maxSize; $pos != $this->real; $pos = ($pos + 1) % $this->maxSize) { $keys[] = $this->getKeyByPos($pos); } return $keys; } private function add($pos, $data) { $this->memcache->add($this->getKeyByPos($pos), $data); return $this; } private function increment($pos) { return $this->memcache->increment($this->getKeyByPos($pos)); } private function decrement($pos) { $this->memcache->decrement($this->getKeyByPos($pos)); } private function set($pos, $data) { $this->memcache->set($this->getKeyByPos($pos), $data); return $this; } private function get($pos) { return $this->memcache->get($this->getKeyByPos($pos)); } private function delete($pos) { return $this->memcache->delete($this->getKeyByPos($pos)); } private function getKeyByPos($pos) { return $this->prefix . $this->name . $pos; } } |
主要是考虑到QQ的PHP SDK写的真是太烂了,纯属是普及API知识,而不是到手就可以部署的类库。。反正自己都写了一个了,就拿出来分享下。。
什么也不多说,直接上代码。
Qq_sdk.php
代码如下 | 复制代码 |
<?php /** * QQ开发平台 SDK * 作者:偶尔陶醉 * blog: www.stutostu.com */
class Qq_sdk{
//配置APP参数 private $app_id = 你的APP ID; private $app_secret = ‘你的APP_secret’; private $redirect = 你的回调地址;
function __construct() {
}
/** * [get_access_token 获取access_token] * @param [string] $code [登陆后返回的$_GET['code']] * @return [array] [expires_in 为有效时间 , access_token 为授权码 ; 失败返回 error , error_description ] */ function get_access_token($code) { //获取access_token $token_url = ‘https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&’ . ‘client_id=’ . $this->app_id . ‘&redirect_uri=’ . urlencode($this->redirect)//回调地址 . ‘&client_secret=’ . $this->app_secret . ‘&code=’ . $code; $token = array(); //expires_in 为access_token 有效时间增量 parse_str($this->_curl_get_content($token_url), $token);
return $token; }
/** * [get_open_id 获取用户唯一ID,openid] * @param [string] $token [授权码] * @return [array] [成功返回client_id 和 openid ;失败返回error 和 error_msg] */ function get_open_id($token) { $str = $this->_curl_get_content(‘https://graph.qq.com/oauth2.0/me?access_token=’ . $token); if (strpos($str, “callback”) !== false) { $lpos = strpos($str, “(“); $rpos = strrpos($str, “)”); $str = substr($str, $lpos + 1, $rpos – $lpos -1); } $user = json_decode($str, TRUE);
return $user; }
/** * [get_user_info 获取用户信息] * @param [string] $token [授权码] * @param [string] $open_id [用户唯一ID] * @return [array] [ret:返回码,为0时成功。msg为错误信息,正确返回时为空。...params] */ function get_user_info($token, $open_id) {
//组装URL $user_info_url = ‘https://graph.qq.com/user/get_use . ‘access_token=’ . $token . ‘&oauth_consumer_key=’ . $this->app_id . ‘&openid=’ . $open_id . ‘&format=json’;
$info = json_decode($this->_curl_get_content($user_info_url), TRUE);
return $info; }
private function _curl_get_content($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); //设置超时时间为3s curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3); $result = curl_exec($ch); curl_close($ch);
return $result; }
}
/* end of Qq_sdk.php */
|
使用方法:在你网站上放置超链接,地址为:https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=你的APP_ID&redirect_uri=你的回调地址
在回调地址上调用我上面这个qq_sdk即可。
demo如下:
代码如下 | 复制代码 |
if(empty($_GET['code'])) { exit(‘参数非法’); }
include(‘qq_sdk’); $qq_sdk = new Qq_sdk(); $token = $qq_sdk->get_access_token($_GET['code']); print_r($token);
$open_id = $qq_sdk->get_open_id($token['access_token']); print_r($open_id);
$user_info = $qq_sdk->get_user_info($token['access_token'], $open_id['openid']); print_r($user_info); |
识别图片主色调这个,网上貌似有几种方法,不过,最准确,最优雅的解决方案还是利用聚类算法来做。。。
直接上代码。。。。不过,我测试结果表示,用PHP来做,效率不佳,PHP不适合做这种大规模运算~~~,用nodejs做 效率可以高出100倍左右。。。
代码如下 | 复制代码 |
<?php $start = microtime(TRUE); main();
function main($img = ‘colors_files/T1OX3eXldXXXcqfYM._111424.jpg’) {
list($width, $height, $mime_code) = getimagesize($img);
$im = null; $point = array(); switch ($mime_code) { # jpg case 2: $im =imagecreatefromjpeg($img); break;
# png case 3:
default: exit(‘擦 ,什么图像?解析不了啊’); }
$new_width = 100; $new_height = 100; $pixel = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($pixel, $im, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
run_time();
$i = $new_width; while ($i–) { # reset高度 $k = $new_height; while ($k–) { $rgb = ImageColorAt($im, $i, $k); array_push($point, array(‘r’=>($rgb >> 16) & 0xFF, ‘g’=>($rgb >> 8) & 0xFF, ‘b’=>$rgb & 0xFF)); } } imagedestroy($im); imagedestroy($pixel);
run_time();
$color = kmeans($point);
run_time();
foreach ($color as $key => $value) &nb echo ‘<br><span style=“background-color:’ . RGBToHex($value[0]) . ‘” >’ . RGBToHex($value[0]) . ‘</span>’; }
}
function run_time() { global $start; echo ‘<br/>消耗:’, microtime(TRUE) – $start; }
function kmeans($point=array(), $k=3, $min_diff=1) { global $ii; $point_len = count($point); $clusters = array(); $cache = array();
for ($i=0; $i < 256; $i++) { $cache[$i] = $i*$i; }
# 随机生成k值 $i = $k; $index = 0; while ($i–) { $index = mt_rand(1,$point_len-100); array_push($clusters, array($point[$index], array($point[$index]))); }
run_time(); $point_list = array();
$run_num = 0;
while (TRUE) { foreach ($point as $value) { $smallest_distance = 10000000;
# 求出距离最小的点 # index用于保存point最靠近的k值 $index = 0; $i = $k; while ($i–) { $distance = 0; foreach ($value as $key => $p1) { &n { $distance += $cache[$p1 - $clusters[$i][0][$key]]; } else { $distance += $cache[$clusters[$i][0][$key] – $p1]; } }
$ii++;
if ($distance < $smallest_distance) { $smallest_distance = $distance; $index = $i; } } $point_list[$index][] = $value; }
$diff = 0; # 1个1个迭代k值 $i = $k; while ($i–) { $old = $clusters[$i];
# 移到到队列中心 $center = calculateCenter($point_list[$i], 3); # 形成新的k值集合队列 $new_cluster = array($center, $point_list[$i]); $clusters[$i] = $new_cluster;
# 计算新的k值与队列所在点的位置 $diff = euclidean($old[0], $center); }
# 判断是否已足够聚合 if ($diff < $min_diff) { break; }
} echo ‘—>’.$ii;
return $clusters; }
# 计算2点距离 $ii = 0; function euclidean($p1, $p2) {
$s = 0; foreach ($p1 as $key => $value) {
$temp = ($value – $p2[$key]); $s += $temp*$temp; }
return sqrt($s);
}
# 移动k值到所有点的中心 function calculateCenter($point_list, $attr_num) { $vals = array(); $point_num = 0;
$keys = array_keys($point_list[0]); foreach($keys as $value) { $vals[$value] = 0; }
foreach ($point_list as $arr) { $point_num++; foreach ($arr as $key => $value) { $vals[$key] += $value; } }
foreach ($keys as $index) { $vals[$index] = $vals[$index] / $point_num; }
return $vals; }
function RGBToHex($r, $g=”, $b=”) { if (is_array($r)) { $b = $r['b']; $g = $r['g'];
}
$hex = “#”; $hex.= str_pad(dechex($r), 2, ’0′, STR_PAD_LEFT); $hex.= str_pad(dechex($g), 2, ’0′, STR_PAD_LEFT); $hex.= str_pad(dechex($b), 2, ’0′, STR_PAD_LEFT);
return $hex; } ?> |
代码如下 | 复制代码 |
<?php
|
相关文章
- eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
- 在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
Python astype(np.float)函数使用方法解析
这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08- 这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
- 本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
- 下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
- CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
Android开发中findViewById()函数用法与简化
findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20- 这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
- strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
PHP函数分享之curl方式取得数据、模拟登陆、POST数据
废话不多说直接上代码复制代码 代码如下:/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含POST、HEADER等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header:...2014-06-07- Foreach 函数(PHP4/PHP5)foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。...2013-09-28
- free函数是释放之前某一次malloc函数申请的空间,而且只是释放空间,并不改变指针的值。下面我们就来详细探讨下...2020-04-25
- PHP 函数 strip_tags 提供了从字符串中去除 HTML 和 PHP 标记的功能,该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数...2014-05-31
SQL Server中row_number函数的常见用法示例详解
这篇文章主要给大家介绍了关于SQL Server中row_number函数的常见用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08- 分享一个PHP加密解密的函数,此函数实现了对部分变量值的加密的功能。 加密代码如下: /* *功能:对字符串进行加密处理 *参数一:需要加密的内容 *参数二:密钥 */ function passport_encrypt($str,$key){ //加密函数 srand(...2015-10-30
- 首先来看下流程:流程原理: 1.通过code获得access_token通过授权,并获取用户的信息(包括用户u_id)(这个u_id在后面的第三方登录表里面叫sina_id,那个表是需要自己建的) 2.查询第三方登录表,如果不存在用户sina_id,分2...2014-05-31
php的mail函数发送UTF-8编码中文邮件时标题乱码的解决办法
最近遇到一个问题,就是在使用php的mail函数发送utf-8编码的中文邮件时标题出现乱码现象,而邮件正文却是正确的。最初以为是页面编码的问题,发现页面编码utf-8没有问题啊,找了半天原因,最后找到了问题所在。 1.使用 PEAR 的...2015-10-21- 下面小编就为大家带来一篇C#中加载dll并调用其函数的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
- 这篇文章主要介绍了C#虚函数用法,实例分析了C#中虚函数的功能与基本使用技巧,需要的朋友可以参考下...2020-06-25