开发者

CakePHP What is the best way to retrieve database information in a helper? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 8 years ago.

开发者_如何学JAVA Improve this question

What is the correct way to retrieve Database information using a custom cakePHP helper?


the short answer is - no. You need to pull the data from the Controller and pass it to the view from where the helper will get it.

I had the same heretic ideas in the beginning when I started with MVC pattern. :)


There is no correct way for finding database info in a helper, and you should avoid it.

But there is a way of doing it in helpers and views: $posts = ClassRegistry::init('Post')->find('all');

Again, you are recommended not to use Models in views and you will thank yourself later.


i dont agree with the concept that i may not use database result in helper. because suppose i am trying to show dynamic links in side bar or in footer i have to put the result in each method in my every controller. so it is easy to call the function in helper that make a element and call that helper in it.

now you can call database results in helper just like this

ClassRegistry::init('Post')->find('all'); As written by fahad.

and for the note if you have made some method in the post model you can call that too like this ClassRegistry::init('Post')->custom_function_name($params);


If you want to have dynamic links on every page then write a component that grabs the links from the db, and then sets the variable in the controller so the view knows about it. Have you AppController use the Component and if you write it correctly you won't ever have to include it in any action.

http://github.com/markstory/cakephp_menu_component

Or...

Write an element that uses requestAction and caches the menus. Include this element in your view when you need it.

http://bakery.cakephp.org/articles/view/creating-reusable-elements-with-requestaction

Or...

Run the code in your AppController::beforeFilter method and assign the view variable that way.

http://book.cakephp.org/view/984/Callbacks

Any of these methods are MVC correct while instancing a model in your view is not correct and there isn't any room to argue about it. Do it the right way and save yourself the headaches later while learning about how CakePHP can keep your code DRY

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜