I have a class with a few rather large methods. In it’s basic and most common state most of the functionality is not required though, so I was wondering if there is a way of lazy loading just parts of the class. The methods need to be able to access private/protected members so it would be ideal if the methods were native to the class, however in looking for other solutions I came across this which discusses using private members in callbacks which would be a workable solution (I’d use separate classes that contain a function that calls the callback and lazy load that class). That was 2009 though and whether this functionality has been removed in later versions of PHP i don’t know, but it doesn’t seem to be working here with 5.3.5
Is there a way of doing this, or do you have any suggestions for other patterns I should be looking at?
Thanks.
Wow! Thanks for all the answers. I think the point a number of you make regarding this being a probable premature optimization, or worse, not an optimization at all is very valid and I will be doing profiling to check that any solution I settle on is actually helping not hurting.
…
Now to read and digest all your thoughts properly. Thanks again.
As of PHP 5.4 you can (re-)bind Anonymous Functions and Closures:
See https://wiki.php.net/rfc/closures/object-extension for a discussion of the Closure implementation and potential gotchas.
In general, if you find your class has many long methods, try to break them down into smaller chunks. Describe what the methods do in plain english. For every “and” make a new method and move the code there.
Also have a look at the various properties in that class. If some of them go conceptually together, consider making them into an object of their own. Move any methods accessing those properties to the new object for cohesion.
I also somewhat question your motives for wanting to “lazy load” methods into the class. There is no performance complication for having them there, even when you dont use them. If this is for a performance optimization, you are probably approaching it from the wrong end.
Another option would be to use Traits or, even simpler, Composition.