douxieshang5577 2015-02-26 20:04
浏览 117
已采纳

PhalconPHP视图/布局/控制器

I am new in Phalcon .I create a PhalconPHP application which is get menu elements from database. I use a layout to create the menu which is called in index.volt, but the layout call directly the model function. I think this is not the best solution maybe i should use a controller between model and layout.

enter image description here

layout:

<?php

$menus = Menus::find();

foreach ($menus as $menu) {
    echo "<li>".$menu->name."</li>";
}

index:

<!DOCTYPE html>
<html>
    <head>
        <title>Phalcon PHP Framework</title>
    </head>

            <?php $this->partial("layouts/menus") ?>
        {{ content() }}

</html>

I would really appreciate, that somebody tell me what is the best solution for that.

  • 写回答

1条回答 默认 最新

  • doutuobao4004 2015-03-02 09:32
    关注

    In case of generating menu, you are looking probably for extending yout BaseController class. It's quite good practice for generating content you need on all your controllers like menu, meta-data or breadcrumbs.

    class BaseController extends \Phalcon\Mvc\Controller {
        function initialize() {
    
            $menus = Menus::find(array(
                 // you may want to condition query based on user cookie
                 // or controller you are in
                'conditions' => 'controller = "' . $this->dispatcher->getControllerName() . '"'
            ));
    
            // and set it as View variable to use it if you want
            $this->view->setVar('menus', $menus);
        }
    }
    

    And set all your controllers to use that as default:

    class DefaultController extends BaseController { }
    

    Than in menus.phtml:

    <?php
    
        foreach ($menus as $menu) {
            echo "<li>".$menu->name."</li>";
        }
    

    should be enough. Looks better in Volt:

    <ul>
    {% for menu in menus %}
        <li>
            <a href="{{ menu.url }}">{{ menu.name }}</a>
        </li>
    {% enfor %}
    

    In case of more complex problems, like generating content only on 50% of your pages, you may want to put into View only parameters, eg.:

    $this->view->setVar('menus', array(
        'conditions' => 'controller = "' . $this->dispatcher->getControllerName() . '"'
    ));
    

    but that may be considered as not an elegant solution and is not preventing you from getting your hands on model in your View, what I assume you'd like to avoid. Slightly better would be setting an built query of queryBuilder and running its ->execute() in view loop, to not stress DB as long as it's not necessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 amesim液压仿真问题
  • ¥15 解密代码希望师傅们解一下!
  • ¥15 MATLAB优化设计
  • ¥15 ANN预测模型 200大米
  • ¥20 优秀学生的问题 oj java
  • ¥15 导师让训练数据集,但是原图和标注图在一起,怎么办呢
  • ¥15 scratch-gui 如何集成进 react native
  • ¥15 把全局悬浮窗改为局内悬浮窗
  • ¥15 Excel vba编程调用word如何读取换行符
  • ¥15 在proteus 中画好电路编号程序后灯泡无法点亮是什么原因