PHP回调与模板
我构建了一个列表呈现类:PHP回调与模板,php,oop,templates,callback,Php,Oop,Templates,Callback,我构建了一个列表呈现类: class ListRenderer { /** * @param int $columns number of columns * @param string $element container element * @param string $styleClass container style */ public function __construct($columns,$element='div',$s
class ListRenderer
{
/**
* @param int $columns number of columns
* @param string $element container element
* @param string $styleClass container style
*/
public function __construct($columns,$element='div',$styleClass=''){...}
...
/**
* @param mixed $callback function to render items - should take two
* parameters ($item,$index)
* @param array $list items to render
*/
public function renderArrayList($callback,$list){...}
/**
* @param mixed $callback function to render items - should take 3 parameters
* ($row,$i,$count) $i and $count are the position and total items
* @param string $sql query string
* @param string $errorMessage
* @param int $blanks number of blank items to render. The callback will be
* invoked with a null $row parameter for the blank records.
*/
public function renderQueryList($callback,$sql,$errorMessage,$blanks=0){...}
...
}
回调函数呈现单个项
这也可以通过使用模板来实现:
class ListRenderer
{
...
//$itemRenderer implements ListItemRenderer
public function renderArrayList($itemRenderer,$list){...}
//$itemRenderer implements ListItemRenderer
public function renderQueryList($itemRenderer,$sql,$errorMessage,$blanks=0){...}
...
}
template ListItemRenderer
{
public function renderArrayItem($item,$index);
public function renderQueryItem($row,$index,$count);
}
class SomeClass implements ListItemRenderer
{
...
public function renderArrayItem($item,$index){...}
public function renderQueryItem($row,$index,$count){...}
...
}
我不知道为什么我在这一次被召回;来自Java背景的我通常倾向于使用第二种方法
在我看来:
- 回调更灵活
- 例如,模板将单个类限制为一个renderArrayItem函数,其中回调将允许每个类为此使用多个函数
- 模板方法要求函数是类成员
- 回调倾向于生成可维护性较差的代码
在这件事上,有什么强有力的理由可以这样或那样做吗?一个原因与另一个原因、另一个原因可能有多种原因。特别是对于你的情况,我不知道区别是什么,因为我不知道你的申请 所以我反问:为什么一个对另一个?如果您仍然不知道该走哪条路,或者不确定是否需要明确的一条或另一条,为什么不创建一个回调变量,以便在需要时使用?您可以在实例化类时插入回调:
class ListItemCallbackRenderer implements ListItemRenderer
{
private $callbacks;
public function __construct(array $callbacks)
{
$this->callbacks = $callbacks;
}
public function renderArrayItem($item,$index)
{
$callback = $this->callbacks[__FUNCTION__];
// ...
}
public function renderQueryItem($row,$index,$count)
{
$callback = $this->callbacks[__FUNCTION__];
// ...
}
}
这样,界面保持不变,这使您的整体设计更加流畅,您可以决定在应用程序中的任何地方使用哪种变体。实际上,没有必要把自己贬为一种方法。你有没有遇到任何具体的问题,或者你只是要求扔硬币?如果是这样,请定义“强”。我只是在寻找一些反馈。你说的“强”是什么意思?你问的是“强的理由”,所以我问你说的“强”是什么意思。这两种方法似乎没有太大区别。我想知道是否有什么东西可以让一种方法成为显而易见的最佳选择。