Greetings,
is it possible to overload the constructor for a Page Model?
TIA
D
Greetings,
is it possible to overload the constructor for a Page Model?
TIA
D
You can’t overload constructors in PHP in general, but I don’t really see why you would need to do this for Page models anyway. What are you trying to do?
Well this stems from Page Model vs Controller.
I have some calculated bits of data that I wish to add to $page.
However to calculate this data I have to create an array of page uids, do a bit of massaging, store it into an array, work out a position, etc etc etc.
Now since I wish to return 2 or more separate items from this calculated data to my script so $page->item1(), $page->item2() however in the Page Model concept I would have to do all of the calculations within each item’s function - so repeated code which obviously is not ideal.
If I move this to a Controller then the controller starts to get lengthy and bogged down with code and becomes quite unreadable.
Currently I am returning an information array, so I was wondering what I should do about it. The constructor seems a logical place for the calculations simply because I can create the array there and access its contents elsewhere.
TIA
D
Well, you can overwrite the __construct()
method just like any other method:
public function __construct($parent, $dirname) {
parent::__construct($parent, $dirname);
// Do your custom stuff
}
You could also create a separate private method that contains the common code and caches the result in an instance var. It can then return the cache instead of redoing the calculations. This method would be called by both of your public methods.
A separate method is actually more elegant as it only computes the data if it is actually being used somewhere on the current page.
You are way too fast in replying, @lukasbestle
That’s part of my job.
@lukasbestle Thank you for the answer. You have both answered my previous question AND supplied me with an alternative.
D