Question

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

Était-ce utile?

La solution

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top