【问题标题】:Adding properties to an object using a fluent interface使用流畅的接口向对象添加属性
【发布时间】:2012-10-08 09:07:27
【问题描述】:

我有一个像下面这样的课程:

$structure = new stdClass();

$structure->template->view_data->method       = 'get_sth';
$structure->template->view_data->lang         = $lang;
$structure->template->view_data->id_page      = $id_page;
$structure->template->view_data->media_type   = 'ibs';
$structure->template->view_data->limit        = '0';
$structure->template->view_data->result_type  = 'result';

我很好奇它是否可以像下面这样写?

$structure->template->view_data->method       = 'get_sth_else',
                               ->lang         = $lang,
                               ->id_page      = $id_page,
                               ->media_type   = 'ibs',
                               ->limit        = '0',
                               ->result_type  = 'result',

                    ->another-data->method    = 'sth_else',
                                  ->type      = 'sth',
                                  ->different = 'sth sth';

【问题讨论】:

  • 你不能使用你的语法,但是你可以在每个setter中返回$this以便调用setA($a) -> setB($b) -> ... -> setZ($z)
  • 他们可以通过重载 __call 函数来重载 set* 函数来使其更容易。

标签: php codeigniter object fluent-interface


【解决方案1】:

不行,每次都要传递对象和值:

$structure->template->view_data->method       = 'get_sth_else';
$structure->template->view_data->lang         = $lang;
$structure->template->view_data->id_page      = $id_page;
$structure->template->view_data->media_type   = 'ibs';
$structure->template->view_data->limit        = '0';
$structure->template->view_data->result_type  = 'result';

$structure->template->another_data->method    = 'sth_else';
$structure->template->another_data->type      = 'sth';
$structure->template->another_data->different = 'sth sth';

【讨论】:

  • 在使用 Codeigniter 中的活动记录时,我们可以以某种方式链接方法,所以我相信它也应该是一种方式......
  • 我相信你,但对象是不可链接的。
【解决方案2】:

您所说的称为“Fluent Interface”,它可以使您的代码更易于阅读。

它不能“开箱即用”,您必须设置类才能使用它。基本上,您想在流畅接口中使用的任何方法都必须返回其自身的实例。所以你可以这样做:-

class structure
{
    private $attribute;
    private $anotherAttribute;

    public function setAttribute($attribute)
    {
        $this->attribute = $attribute;
        return $this;
    }

    public function setAnotherAttribute($anotherAttribute)
    {
        $this->anotherAttribute = $anotherAttribute;
        return $this;
    }

    public function getAttribute()
    {
        return $this->attribute;
    }

    //More methods .....
}

然后这样称呼它:-

$structure = new structure();
$structure->setAttribute('one')->setAnotherAttribute('two');

显然,这对 getter 不起作用,因为它们必须返回您要查找的值。

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    相关资源
    最近更新 更多