知修

知而修之方为悟

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

有时为了方便和高效,我们更喜欢使用foreach … in .. 结构来遍历数据

对于PHP强大的array在大多数情况下都能满足我们的需要

不过,当array定义的数据结构不能满足我们的需要时,就不得不自己来写Iterator了

比如,PDO中提供了bindParam来动态绑定参数,具有防止注入及重复利用资源的功能

如果直接使用其提供的方法也无防,不过对于大多数项目都要有自己的数据库操作层

在封装这个DB操作层的时候,对于动态绑定的参数如何传递呢?

如果用array,则只能提供key与value,db的type等就不能提供了(使用分割符也可以,不过太过ugly)

为此,我们可以自定义以下类:

class DBParam{...}  //代表一个参数
class DBParams{...}  //代表一组参数

其中DBParam中提供bindParam需要的参数信息,实现类似如下:

class DBParam
{
    private $_key,
            $_value,
            $_type;//如果需要可以再加上size等参数

    public function __construct($key,$value,$type=PDO::PARAM_STR)
    {
         $this->_key = $key;
         $this->_value = $value;
         $this->_type = $type;
    }
    
    public function getKey()
    {
        return $this->_key;
    }
    
    public function getValue()
    {
        return $this->_value;
    }
    
    public function getDBType()
    {
        return $this->_type;
    }
}
而DBParams我们是希望能够使用foreach … in …进行遍历的 ,因为我们会像如下代码这样使用它:
    function fetchXXX($sql,LQP_DBParams &$params=null)
    {
        ....
        $stat = $this->_dbh->prepare($sql);
        if($params != null)
        {
            foreach($params as $p)
            {
                $stat->bindParam($p->getKey(),$p->getValue(),$p->getDBType());
            }
        }
        $stat->execute();
        ....
     }

那如何让DBParams支持foreach呢?一般我们可以让它继承Iterator接口,重写大量的方法,过于繁琐,这里我们直接让其从IteratorAggregate继承:

class DBParams implements IteratorAggregate
{
    private $_params = array();
    public function add(LQP_DBParam $param)
    {
        array_push($this->_params, $param);
    }

    //实现的方法    
public function getIterator() { return new ArrayIterator($this->_params); }
}
posted on 2010-07-06 01:24  BoolYang  阅读(558)  评论(0编辑  收藏  举报