Reputation: 319
I beginning experimenting with CakePHP, and I am contemplating whether calculation, probably business, logic that would determine what gets presented on the View should be in the view or somewhere else.
The issue why I end up putting them in the view is because the data is only available when I do a foreach loop. Here is a simple example:
<?php foreach ($records as $record):
$amountDifference = $record['Record']['outstanding'] - $record['Record']['paid'];
if ($amountDifference > 5){
echo "greater than 5";
}else{
echo "less than 5";
}
endforeach; ?>
What do you all say?
Upvotes: 1
Views: 243
Reputation: 13952
A few things to point out...
First, in this case, your code is fine as is. It's simple stuff, so I'd say it doesn't matter too much if it's in the model or the view.
The issue why I end up putting them in the view is because the data is only available when I do a foreach loop.
Second, and more importantly, it's important to know that the "foreach" loop is no barrier, and you could easily do that in your model if you wanted. You'd just make a method in your model something like this:
public function findAllWithAmountDifference(){
$records = $this->find('all');
// Now go through your records and adjust, before returning them
foreach ($records as &$record):
$record['Record']['difference'] = $record['Record']['outstanding'] - $record['Record']['paid'];
endforeach;
// Now your return value will have extra array keys with the difference
return $records;
}
And third, I would say that the best way to do it in this particular case would be to use virtual fields (http://book.cakephp.org/2.0/en/models/virtual-fields.html), so the calculations take place as part of the database query.
Last, there is obviously not always a totally clear cut between what is deemed presentation logic, and what is deemed business logic. In simple cases like yours, it could go either way, and it's not worth losing sleep over.
Strictly speaking, calculating the difference between two values is manipulation of data, and therefore belongs in the model.
Having said that, if you think your code will be more transparent, and easier to understand and maintain, with that code in your view rather than your model, the just put it in the view!
The thing about code theory and best practices is that they are intended as a general guide to making your code easier to debug / read / extend / maintain. Usually, they're pretty good, but they're not absolute rules. And in cases where violating a rule or best practice will genuinely make your code easier to debug / read / maintain, then fine! Violate away!
Upvotes: 1