Reputation: 1781
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.
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.
Upvotes: 3
Views: 824
Reputation: 4980
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.
Upvotes: 3