I have two tables: Campaigns, Campaign_statistics. I need to output campaigns list with nested statistics.
To start, I just had a method in model which created an array like the following:
array(
'id', // integer
'campaign_name',// string
'stats'// nested array of arrays with stats by periods
);
In a view I had two foreach loops (one nested inside another):
<? foreach ($this->campaigns as $campaign): ?>
<div class="campaign">
<?= $campaign['name'] ?>
<? foreach($campaign['stats'] as $monthStats): ?>
<div class="statistics">
<?= $monthStats['views'] ?>
</div>
<? endforeach ?>
</div>
<? endforeach ?>
That implementation of a model results in messy code, so I decided to try to make Campaign an object. In a view I make use of getters:
<? foreach($this->campaigns as $campaign): ?>
<div class="campaign">
<?= $campaign->getName() ?>
<? foreach($campaign->getMonthStats() as $monthStats): ?>
<div class="statistics">
<?= $monthStats->getViews() ?>
</div>
<? endforeach ?>
</div>
<? endforeach ?>
I’ve never seen any framework uses getters like this. What are pros/cons of this approach?
The beauty with getters in object oriented design is that they hide the complexity of how the returned result is computed. So you can change the way you are computing the views and its automatically updated across all applications.
Purists claim that you should not have method calls in views etc, but pragmatists like myself say, put method calls in views since methods can be unit tested. However when you find that the outputs are becoming too complex (Martin Fowler calls this objects becoming too intimate with each other), then you need to refactor to use a single method call.
Bottom line: Methods good because their outputs can be verified