gpt4 book ai didi

view - PhalconPHP View /布局/ Controller

转载 作者:搜寻专家 更新时间:2023-10-31 20:38:45 24 4
gpt4 key购买 nike

我是 Phalcon 的新手。我创建了一个 PhalconPHP 应用程序,它从数据库中获取菜单元素。我使用布局创建在 index.volt 中调用的菜单,但布局直接调用模型函数。我认为这不是最好的解决方案,也许我应该在模型和布局之间使用 Controller 。

enter image description here

布局:

<?php

$menus = Menus::find();

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

索引:

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

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

</html>

如果有人能告诉我最好的解决方案是什么,我将不胜感激。

最佳答案

在生成菜单的情况下,您可能正在寻找扩展您的 BaseController 类。在所有 Controller 上生成您需要的内容(例如菜单、元数据或面包屑)是一种很好的做法。

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);
}
}

并将所有 Controller 设置为默认使用它:

class DefaultController extends BaseController { }

比起在 menus.phtml 中:

<?php

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

应该够了。在 Volt 中看起来更好:

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

如果出现更复杂的问题,例如只在 50% 的页面上生成内容,您可能需要将参数放入“仅查看”中,例如:

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

但这可能被认为不是一个优雅的解决方案,并且不会阻止您在 View 中使用模型,我认为您希望避免这种情况。稍微好一点的是设置一个内置查询 queryBuilder并在 View 循环中运行它的 ->execute(),只要没有必要,就不会给 DB 带来压力。

关于view - PhalconPHP View /布局/ Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28751741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com