0

I'm building a new framework and beneath all the work I'm suffering a strange question aroused my mind. Is it worth creating a jquery-like nesting syntax like this ?

core->component->...->method()

Assuming all "components" expand an abstract class and the core is like

class core {
     public $components = array();
     public load ($component) {
          //Assuming component exists
          include($component);
          $this->component = new component_name($parameters);
          //This last line might be as well included in "component"'s constructor
          $this->component->core_link = $this;

          $components[] = $component;
     }
}

Is this "architecture" right or does it sound weird in PHP ? Is it easy to read/learn ? Is there any tip you'd give me ?

Thanks

Kei
  • 771
  • 6
  • 17

1 Answers1

0

There are a number of PHP frameworks/libraries which utilize such a fluent programming style (also known as method chaining, method cascading, etc.). So I don't think there is anything wrong with this approach. I personally use it a lot.

Your implementation is incorrect however. Basically, each method call that would be subject to chaining must return an instantiated object to allow subsequent method calls to be made against it.

For example, say I wanted to modify your load() method to allow chaining on the new component_name object that is loaded. That might look like this:

 public load ($component) {
      //Assuming component exists
      include($component);
      $this->component = new component_name($parameters); // not sure where $parameters comes from in your code here
      $components[] = $component;
      return $this->component;
 }

And usage would be:

$core_object->load('some_component_name')->some_method_on_component_name();
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Thanks for the reply, since "load" itself is a component which I call "dead end", no further chaining is allowed and a method must be called to end the chain. Thanks for sharing the name I longed for and couldn't find, and for pointing out how further chaining is done. – Kei Dec 05 '13 at 17:11
  • @Kei Sometimes one would opt to simply do `return $this` on all methods that are not expected to return a discrete value (like a getter method), even those you are noting as "dead end". This is so that chaining is made reliable. Example usage: `$components_including_newly_loaded_one = $core_object->load('xyz')->get_components()` – Mike Brant Dec 05 '13 at 17:46