构建页眉和页脚的最佳方法是什么?你应该从 Controller 中调用它,还是从 View 文件中包含它?我正在使用 CodeIgniter,我想知道对此的最佳做法是什么。从 Controller 加载所有包含的 View 文件,像这样?
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('header');
$this->load->view('menu');
$this->load->view('content', $data);
$this->load->view('footer');
}
}
或调用单个 View 文件,并从那里调用页眉和页脚 View :
//controller file
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('content', $data);
}
}
//view file
<?php $this->load->view('header'); ?>
<p>The data from the controller</p>
<?php $this->load->view('footer'); ?>
我已经看到它是双向的,但现在想在我走得太远之前做出选择。
最佳答案
实际上,在我自己对此进行了相当多的研究之后,我得出的结论是,在 MVC 中包含页眉和页脚的最佳实践是第三种选择 - 即扩展基本 Controller 。这将为您提供比文本建议更多的灵 active ,特别是如果您正在构建一个非常模块化的布局(不仅仅是页眉和页脚,还有侧边栏面板、非静态菜单等)。
首先,定义一个 Base_controller
类,您可以在其中创建将页面元素(页眉、页脚等)附加到输出字符串的方法:
class Base_controller extends Controller
{
var $_output = '';
function _standard_header($data=null)
{
if (empty($data))
$data = ...; // set default data for standard header here
$this->_output .= $this->load->view('header', $data, true);
}
function _admin_header($data=null)
{
if (empty($data))
$data = ...; // set default data for expanded header here
$this->_output .= $this->load->view('admin_header', $data, true);
}
function _standard_page($data)
{
$this->_standard_header();
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output; // note: place the echo statement in a
// separate function for added flexibility
}
function _page_with_admin_header($data)
{
$this->_admin_header($data);
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output;
}
}
然后,在您的页面 Controller 中,只需扩展基类并调用您的函数来构建页面。
class Page_controller extends Base_controller
{
function index()
{
$data = ...; // Set content data here
$this->_standard_page($data);
}
function admin()
{
$data = ...; // Set content and header data here
$this->_page_with_admin_header($data);
}
}
使用基本 Controller ,您可以在各个页面 Controller 中实现非常简洁的代码,并为页面上的元素提供单独的 View (允许在 View 和 Controller 中重用代码)。您需要做的就是将您的公共(public)页面“部分”(您可能会被称为“片段”)定义为基本 Controller 中的函数。
如果基础 Controller 开始无法控制地增长(这可能发生在大型网站上),您可以通过将其放置在子类中并让相应的页面 Controller 扩展它们而不是原始基础来重新排列它的一些不太通用的功能 Controller 。
享受吧!
关于php - 最佳实践 : What's the Best Way for Constructing Headers and Footers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/176856/