加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP队列用法实例

发布时间:2020-12-13 02:08:12 所属栏目:PHP教程 来源:网络整理
导读:《:PHP队列用法实例》要点: 本文介绍了:PHP队列用法实例,希望对您有用。如果有疑问,可以联系我们。 本篇章节讲解PHP队列用法.供大家参考研究.具体分析如下: PHP实例 什么是队列,是先进先出的线性表,在具体应用中通常用链表或者数组来实现,队列

《:PHP队列用法实例》要点:
本文介绍了:PHP队列用法实例,希望对您有用。如果有疑问,可以联系我们。

本篇章节讲解PHP队列用法.分享给大家供大家参考.具体分析如下:PHP实例

什么是队列,是先进先出的线性表,在具体应用中通常用链表或者数组来实现,队列只允许在后端进行插入操作,在前端进行删除操作.PHP实例

什么情况下会用了队列呢,并发哀求又要保证事务的完整性的时候就会用到队列,当然不排除使用其它更好的方法,知道的不仿说说看.PHP实例

队列还可以用于减轻数据库服务器压力,我们可以将不是即时数据放入到队列中,在数据库空闲的时候或者间隔一段时间后执行.比如拜访计数器,没有必要即时的执行拜访增加的Sql,在没有使用队列的时候sql语句是这样的,假设有5个人拜访:PHP实例

update table1 set count=count+1 where id=1
update table1 set count=count+1 where id=1
update table1 set count=count+1 where id=1
update table1 set count=count+1 where id=1
update table1 set count=count+1 where id=1PHP实例

而使用队列这后就可以这样:
update table1 set count=count+5 where id=1PHP实例

减少sql哀求次数,从而达到减轻服务器压力的效果,当然访问量不是很大网站根本没有这个必要.
下面一个队列类:
PHP实例

代码如下:
/**
* 队列
*
* @author jaclon
*
*/
class Queue
{
private $_queue = array();
protected $cache = null;
protected $queuecachename;
?
/**
* 构造办法
* @param string $queuename 队列名称
*/
function __construct($queuename)
{
?
$this->cache =& Cache::instance();
$this->queuecachename = 'queue_' . $queuename;
?
$result = $this->cache->get($this->queuecachename);
if (is_array($result)) {
$this->_queue = $result;
}
}
?
/**
* 将一个单元单元放入队列末尾
* @param mixed $value
*/
function enQueue($value)
{
$this->_queue[] = $value;
$this->cache->set($this->queuecachename,$this->_queue);
?
return $this;
}
?
/**
* 将队列开头的一个或多个单元移出
* @param int $num
*/
function sliceQueue($num = 1)
{
if (count($this->_queue) < $num) {
$num = count($this->_queue);
}
$output = array_splice($this->_queue,$num);
$this->cache->set($this->queuecachename,$this->_queue);
?
return $output;
}
?
/**
* 将队列开头的单元移出队列
*/
function deQueue()
{
$entry = array_shift($this->_queue);
$this->cache->set($this->queuecachename,$this->_queue);
?
return $entry;
}
?
/**
* 返回队列长度
*/
function size()
{
return count($this->_queue);
}
?
/**
* 返回队列中的第一个单元
*/
function peek()
{
return $this->_queue[0];
}
?
/**
* 返回队列中的一个或多个单元
* @param int $num
*/
function peeks($num)
{
if (count($this->_queue) < $num) {
$num = count($this->_queue);
}
return array_slice($this->_queue,$num);
}
?
/**
* 消毁队列
*/
function destroy()
{
$this->cache->remove($this->queuecachename);
}
}

希望本文所述对大家的PHP程序设计有所帮助.PHP实例

编程之家培训学院每天发布《:PHP队列用法实例》等实战技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培养人才。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读