简体   繁体   中英

model access from layout file in CakePHP

I am working on a CMS using CakePHP and I want to create a dynamic menu which is the same on all the pages the user can access. So I figured out to create in the layout (since it shared among so many pages and view) but I don't seem to know how to acces the model and get the data from the database to construct the menu. any help is appreciated.

That's because for proper MVC separation * in Cake you're not supposed to access the Model from the View. The only part with access to data should be the Controller (via the Model), which hands it down to the View, which simply displays the data.

As such, using a beforeFilter callback in your global AppController to set() the data is probably the best choice.

In emergencies you can always access anything from anywhere by loading an instance of the needed Class using ClassRegistry::init , but you really shouldn't.


* Actually, in "proper MVC" there's no problem with the View getting data directly from the model. You shouldn't do that in templates necessarily, but View related code can well get data from the model to visualise the model state. It just doesn't really work that way in Cake, because Cake is not proper MVC and default Cake views are only templates.

另一种方法是requestAction ,它允许您从视图/布局中调用控制器操作,然后在这些操作中,您可以访问所需的模型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM