Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
I've been experimenting with some refactoring opportunities in my code and realized that pretty much I am using foreach loops just to iterate trough an array of objects and call some simple method on each of them.
// how about this
foreach($items as $item) {
$item->callSomeMethod();
}
// or this one
$buffer = array();
foreach($items as $key => $item) {
$buffer[$key] = $item->anotherMethod($parameters);
}
// do you recognize them in your code?
Then a breakthrough moment came to me and I realized that this could be a really nice place for __call method.
In fact it looks like some sort of generic composite pattern to me. So what do you think? Could this be useful for you? Any suggestions?
Please read this before posting: I know about Ruby and its blocks support. I don't want to hack PHP to support them. Don't let this be flame about Ruby vs PHP vs something else.
Not so much a pattern more an array object. Very nicely written too. I've written something similar before.
Side-tip: Use self for the name of the current class wherever you can.
ole wrote:Not so much a pattern more an array object.
Actually I think its exactly the composite pattern. http://en.wikipedia.org/wiki/Composite_ ... #Structure You can add, remove components and call methods on composites which call these methods on all components they contain.
ole wrote:Very nicely written too. I've written something similar before.
Thank you!
ole wrote:Side-tip: Use self for the name of the current class wherever you can.
Hmm, what did you mean by this? I don't really understand.
I believe Ole is referring to the fact that the PHP4 use of $this can often be replaced in PHP5 using "self", just as a parent class can be access using "parent". I usually use "self" when calling statics/constants or creating a new object of the same type as the host... Nothing technically wrong with using $this in many cases - maybe Ole can illustrate his observation???
Maugrim_The_Reaper wrote:I usually use "self" when calling statics/constants or creating a new object of the same type as the host... Nothing technically wrong with using $this in many cases - maybe Ole can illustrate his observation???