ob_start() PHP 中模板的替代方案?
问题已更新
我正在构建一个 MVC 框架,对于我的模板和视图,我将有一个主页模板文件,我的视图将包含在该模板中。
我见过的唯一方法是使用输出缓冲
ob_start();
include 'userProfile.php';
$content = ob_get_clean();
还有其他方法可以做到这一点吗?我认为输出缓冲在性能上并不是最好的,因为它使用大量内存
这是一个示例控制器,$this->view->load('userProfile', $profileData);
是将使用输出缓冲加载的部分,以便可以将其包含到下面的主模板中的 $content 部分
视图类
public function load($view,$data = null) {
if($data) {
$this->data = $data;
extract($data);
} elseif($this->data != null) {
extract($this->data);
}
ob_start();
require(APP_PATH . "Views/$view.php");
$content = ob_get_clean();
}
控制器
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
// load a Model
$this->loadModel('profile');
//GET data from a Model
$profileData = $this->profile_model->getProfile($userId);
// load view file
$this->view->load('userProfile', $profileData);
}
}
主站点模板< /强>
<html>
<head>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
Question Updated
I am building an MVC framework, for my templates and views, I will have a main page template file and my views will be included into this template.
The only way I have seen to do this is to use output buffereing
ob_start();
include 'userProfile.php';
$content = ob_get_clean();
Is there any other way of doing this? I think output buffering is not the best on performance as it uses a lot of memory
Here is a sample controller, the $this->view->load('userProfile', $profileData);
is the part that will be loaded using output biffering so that it can be included into the main template below into the $content part
view class
public function load($view,$data = null) {
if($data) {
$this->data = $data;
extract($data);
} elseif($this->data != null) {
extract($this->data);
}
ob_start();
require(APP_PATH . "Views/$view.php");
$content = ob_get_clean();
}
controller
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
// load a Model
$this->loadModel('profile');
//GET data from a Model
$profileData = $this->profile_model->getProfile($userId);
// load view file
$this->view->load('userProfile', $profileData);
}
}
main site template
<html>
<head>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用模板系统不一定与输出缓冲相关。您提供的示例代码中有几件事当然不应该被视为理所当然:
一:
第二:
为什么代码将模板输出捕获到变量中?输出之前是否需要对其进行一些处理?如果没有,您可能会丢失输出缓冲调用并让输出立即发送到浏览器。
Using a template system is not necessarily tied to output buffering. There are a couple of things in the example code you give that should certainly not be taken for granted:
One:
And two:
Why does the code capture the template output into a variable? Is it necessary to do some processing on this before outputting it? If not, you could simply lose the output buffering calls and let the output be sent to the browser immediately.