php5中Iterator与smarty整合 - 马永占 译

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。 http://blog.csdn.net/mayongzhan - 马永占,myz,mayongzhan

php5中Iterator与smarty整合

Iterator(迭代器)在PHP5中是非常重要的,我注意到Iterator在Smarty中不能正常的工作。
Smarty会自动将一个object(对象)转换成array(数组),所以当年在Smarty中循环输出一个object时,模板会自动循环这个object的属性。
例如,建立一个类,然后在函数中定义某些要循环的部分,将这些部分放到protected类型的$_data变量中。
<?php
class MyClass implements Iterator
{
protected $_data = array();

public function rewind()
{
reset($this->_data);
}

public function current()
{
return current($this->_data);
}

public function key()
{
return key($this->_data);
}

public function next()
{
return next($this->_data);
}

public function valid()
{
return $this->current() !== false;
}

public function size()
{
return count($this->_data);
}
}
?>

然后在Smarty使用这个类
{foreach from=$myClassObj item=row}
{$row}
{/foreach}

这样不会输出想要的结果,下面做一下简单的修改,将$myClassObj改成$myClassObj->getData():
{foreach from=$myClassObj->getData() item=row}
{$row}
{/foreach}

这样就能输出正确的结果了。


phpRiot.com: Using the PHP 5 Iterator interface with Smarty

The PHP 5 Iterator interface is very useful for defining custom behaviour for looping over objects, however I just noticed that looping over such objects in Smarty will not work correctly.

Smarty will in fact cast an object back to an array, so when you loop over it, the template will loop over the object's properties (as opposed to using the rules defined by the Iterator methods).

For example, I used code similar to the following to create a class over which I can loop. This lets me loop over the protected $_data array.

<?php
class MyClass implements Iterator
{
protected $_data = array();

public function rewind()
{
reset($this->_data);
}

public function current()
{
return current($this->_data);
}

public function key()
{
return key($this->_data);
}

public function next()
{
return next($this->_data);
}

public function valid()
{
return $this->current() !== false;
}

public function size()
{
return count($this->_data);
}
}
?>

What I want to be able to do is loop over each element in the array with the following code:

{foreach from=$myClassObj item=row}
{$row}
{/foreach}

However, this will not work as expected in Smarty. To get around, I implemented as method called getData() which simply returned the array. This meant my template had to look as follows:

{foreach from=$myClassObj->getData() item=row}
{$row}
{/foreach}

It's a bit annoying to have to do this, since in some ways it defeats the purpose of the using the Iterator interface, but I guess sometimes small sacrifices need to be made.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值