【发布时间】:2017-01-09 10:07:32
【问题描述】:
为了建立一个小型家庭框架,我想将变量发送到视图,但我必须迄今为止找不到有效的解决方案。
有问题的代码:
src/Controller/Controller.php
<?php
namespace App\Controller;
use App\Network\Request;
class Controller {
protected $viewPath = ROOT . VIEW;
protected $template = ROOT . TEMPLATE;
protected $layout = "default";
public function __construct()
{
$request = new Request();
$this->render($request->controller().'/'. $request->action());
}
public function layout($template) {
if($template != $this->layout) {
require $this->template . $template . '.php';
}
}
public function render($view) {
ob_start();
require $this->viewPath . '/' . str_replace('.', '/', $view). '.php';
$content = ob_get_clean();
require $this->template .$this->layout . '.php';
}
public function set($varname) {
extract($varname);
return $varname;
}
}
?>
app/Controller/PostsController.php
<?php
namespace App\Controller;
class PostsController extends Controller {
public function index() {
$posts = [
"id" => "1",
"ids" => "2"
];
$this->set(compact('posts'));
}
}
?>
在 PostsController 中使用 $this->set 函数返回未定义变量:回显后的帖子。
我也尝试将ob_start 和ob_get_clean 放在 set 函数中,但也不起作用。
也就是说,我不想在渲染中包含函数集,因为我动态处理视图的视图(请参阅__construct ())。
另一个问题:
如何将 View 类与我的视图相关联,从而使用 $this->method ()。
谢谢
【问题讨论】:
标签: php function variables frameworks set