2012-11-28 11:25
浏览 31


I am creating a simple website in cakephp.

I have kept header and footer in "element" but my problem is that menu of header is coming from database and it will not be available until I call a function.

I want as soon as controller is called function of menu should be called by own.

图片转代码服务由CSDN问答提供 功能建议


我保留了标题 “元素”中的页脚,但我的问题是标题菜单来自数据库,在调用函数之前它不可用。

我希望控制器调用后立即执行 菜单应该由自己调用。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanhe2027 2012-11-28 11:29

    In your AppController add this:

    function beforeFilter(){
        $this->set('menu', $this->YourModel->findById('Id of your menu data row in database'));

    Then, in the view, the menu will be accessible by calling echo $menu['yourModel']['menu'];

    点赞 打赏 评论
  • dongzhuang6247 2012-11-28 15:28


    Instead of calling the function every time the entire controller (or all controllers) is loaded, it's better practice to just call the function when the element itself is loaded. This allows you much more flexibility moving forward. Eg, maybe the log-in screen doesn't need the menu - or maybe you eventually add an admin tool that has a different menu...etc etc.

    CakePHP makes this VERY easy using requestAction() - read more here:

    Side Note: It's also ideal (MVC pattern and many other reasons) to keep ALL queries in a model, instead of calling them directly from a controller.

    Example Code:

     * MenusController (or any other controller you want)
    public function get_menu_main() {
        $this->set('menu', $this->Menu->getMenuMain());
    public function get_menu_footer() {
        $this->set('menu', $this->Menu->getMenuFooter());
     * Menu model
    public function getMenuMain() {
        return $this->findById('12345');
    public function getMenuFooter() {
        return $this->findById('67891');

    Then, in your element, just use a requestAction to retrieve the data you need for that specific element:

    * MainMenu element
    $menu = $this->requestAction('menus/get_menu_main/');
    * FooterMenu element
    $menu = $this->requestAction('menus/get_menu_footer/');

    Side note: to be a little more proper, you can use $this->Html->url() instead of hard-coding the URLs to the actions.

    Side note: Some of this code might seem like adding extra code when you don't "need" it, but by breaking things up into their correct MVC spot, your code will be much cleaner, more flexible/upgradable...etc etc etc. Getting into a habit of doing things like this will make your life MUCH easier when things start to get even slightly more complicated. (And in all reality, the code above adds a few lines, but as far as complexity is concerned, I think it's easier to understand than having a query in the AppController that loads variables for an element(s). /endrant

    点赞 打赏 评论

相关推荐 更多相似问题