eZ Community » Forums » General » PHP - chaining
expandshrink

PHP - chaining

PHP - chaining

Saturday 22 March 2014 10:51:59 pm - 3 replies

This isn't really an eZ question, but I would greatly appreciate different perspectives.

If you are chaining functions, which is a more appropriate way to code calls to methods?

I have seen both approaches used, and it seems to me the second would run faster. 

$one = $this->getRepository()->getOneService();
$two = $this->getRepository()->getTwoService();
$three = $this->getRepository()->getThreeService();

 

-- or --

 

$repository = $this->getRepository();
$one = $repository->getOneService();
$two = $repository->getTwoService();
$three = $repository->getThreeService();

Sunday 23 March 2014 8:37:39 am

I don't think there is one rule here.

Getting a service isn't a heavy operation. The same object is always returned. As far as I'm concerned, I only create a local reference to a service if I need to use it more than once. That's pretty much all I can say... happy.gif Emoticon

Monday 24 March 2014 3:39:49 pm

I agree with Bertrand that it is more a question of style than substance - for the given case.

You will be getting the same object instance, and there is little to no chance of having some external state change happening in between your getX calls which happen in a row.

Some considerations:

If your code is executed in a tight loop (i.e. many many times), the using a temp variable saves a few function calls. Good for perfs. But the difference is generally negligible

If you debug by using var_dump, then having a variable in there makes it easier to debug. It might save a couple of clicks as well when using a real debugger.

I find long rows with many method calls chained hard to understand. Otoh some of my colleagues have a strong distaste for useless variables.

Tuesday 25 March 2014 8:27:46 am

About "long" chains, I also break them when they lead to lines over 120 characters (our "soft" limit).

expandshrink

You must be logged in to post messages in this topic!

36 542 Users on board!

Forums menu

Proudly Developed with from