我正在尝试 CodeIgniter 和整个 MVC 模式。我已经安装了Colin Williams 的模板库,但是当我试图考虑包含两个菜单/导航的正确方法时,我遇到了困难:一个通用(可能在顶部)和一个特定于每个控制器的侧边栏。
无论哪种方式,它们的位置都不相关,我正在考虑代码的一般结构。现在我的get_menu()
模型中有一个函数,当加载侧边栏的部分模板视图时,它的返回作为参数给出。或者我应该在控制器中执行此操作?
我的一个朋友给我建议不要用 ie a 扩展默认控制器或模型MY_Controller
,但我不知道什么时候实现通用菜单?或者我应该在模板配置文件中对其进行硬编码吗?
我找不到此类任务的指导方针。无论我走到哪里,我都会找到一个新的解决方案,其中许多并不漂亮,其他很多都有很多重复的代码。
编辑。我已经更新了我的代码。我还没有决定如何编写顶部导航(可能是MY_Controller
这样我可以突出显示当前页面)。
MY_Controller.php
abstract class MY_Controller extends CI_Controller {
protected $_nav;
const CONTENT_REGION = 'content';
const NAV_REGION = 'nav';
const TITLE_REGION = 'title';
const SIDEBAR_NAV_TEMPLATE = 'templates/sidebar_nav';
public function __construct() {
parent::__construct();
$this->_load_nav();
}
abstract protected function _get_nav();
protected function _load_nav() {
$this->_nav = array('nav' => $this->_get_nav());
}
protected function _render() {
$args = func_get_args();
$n = func_num_args() - 1;
if ($n < 2) {
return;
}
$this->template->write(self::TITLE_REGION, $args[0]);
for ($i = 1; $i < $n; $i++) {
$this->template->write_view(self::CONTENT_REGION, $args[$i], $args[$n]);
}
$this->template->write_view(self::NAV_REGION, self::SIDEBAR_NAV_TEMPLATE, $this->_nav);
$this->template->render();
}
protected function _set_active_view($active) {
if ($active !== null && isset($this->_nav['nav'][$active])) {
$this->_nav['nav'][$active]['class'] .= ' active';
}
}
}
集合.php
class Collection extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('collection_model');
}
protected function _get_nav() {
return array(
'collection/view' => array(
'href' => 'collection/view',
'value' => 'View collection',
'class' => 'icon-film'
),
'collection/add' => array(
'href' => 'collection/add',
'value' => 'Add title',
'class' => 'icon-plus-sign'
)
);
}
public function index() {
$this->view();
}
public function view() {
$data['list'] = $this->collection_model->get_list();
$this->_set_active_view('collection/view');
$this->_render('View Collection', 'collection/view', $data);
}
}
sidebar_nav.php
<ul class="nav nav-list bs-docs-sidenav">
<?php
foreach ($nav as $item) {
echo '<li';
if ($item['class'] !== null || $item['class'] !== '') {
echo ' class="' . $item['class'] . '"';
}
echo '><a href="' . $item['href'] . '">' . $item['value'] . '</a></li>';
}
?>
</ul>
这看起来怎么样?我可能会编写一个函数_render($title, $view, $data)
来MY_Controller
完成所有模板的工作。你怎么看?
我一直在考虑的另一个解决方案是_get_nav()
从配置文件中删除并加载所需的导航数据,但我不知道该怎么做。