Thursday, October 2, 2008

Does calling model methods from elements break MVC pattern?

It is a question about MVC pattern in cakephp.

I have a calculated value that I want to display in many views, so I
decided to create an element. The business logic has to be performed
in the model, i.e:

models/product.php

class Product extends AppModel {
//... all attributes and methods

function performSomeProductCalculation () {
//perform business logic
return $result;
}
}

There are two options to create an element that renders the result
returned by the above method:

- Option 1: Call the model method directly from element:

views/elements/foo.ctp

<?php
App::import('Model','Product');
$p = New Product();
?>
<div class="result">
The result is <?php echo $p->performSomeProductCalculation() ?>
</div>

- Option 2: Create a controller method for rendering the result, and
call that method in the element via "requestAction"

controllers/products_controller.php

class ProductsController extends AppController {
//... all attributes and method

function my_result() {
return $this->Product->performSomeProductCalculation();
}
}


views/elements/foo.ctp

<?php
$r = $this->requestAction('/products/my_result');
?>
<div class="result">
The result is <?php echo $r; ?>
</div>


Wich options is the correct one in order to respect 100% the MVC
pattern? ? ?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: