Search code examples
phpcodeigniterobjectfluent-interface

Adding properties to an object using a fluent interface


I have a class like below:

$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';

And I am curious about if it can be written like below?

$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';

Solution

  • What you are talking about is called a 'Fluent Interface', and it can make your code easier to read.

    It can't be used 'out of the box', you have to set up your classes to use it. Basically, any method that you want to use in a fluent interface must return an instance of itself. So you could do something like:-

    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 .....
    }
    

    and then call it like this:-

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

    Obviously, this will not work for getters, as they must return the value you are looking for.