문제

I need to make a CakePHP helper which involves making some HTML dynamically. But the part of the code is to make 1-2 database queries. These queries are very essential for this helper as all the text it populates is inside the database.

According to MVC pattern, i should not be making the DB queries in the View (Helper). I am wondering what the best design would be for this case as i want it to align with PHPUnit testing also.

Any ideas would be welcome...

도움이 되었습니까?

해결책

Since the View job is purely to display the (already available) information passed to it from the Controller, I think it would be something like this:

Your controller:

public function foo() {
    $bar = $this->MyModel->find('all');
    $this->set(array('bar' => $bar));
}

Your view:

$result = $this->MyHelper->foo($bar);

다른 팁

You can create a component:

/**
* Set data info
* @access public
* @return void
*/
public function setData()
{
   $data = $this->Model->find('first', $params);
   $this->Controller->set('data', $data);
} 

And print the helper in the layout:

echo $this->MyNewHelper->someHtml($data);

If it's something that could be an Element instead of a Helper, you can use CakePHP's RequestAction [details here] to pull the data needed for the Element.

You can then pass any parameters to the Element, and use those to pass to your controller, which does the model call.

This fits very well with MVC, as the Element only displays the view, but it specifies where it should get it's data (still using the model to retrieve it), which makes it very re-usable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top