在 PHP MVC 中使用多个视图

问题描述 投票:0回答:1

自从我处理 PHP 以来已经有一段时间了,但我正在从头开始做一个项目,并尝试创建一个简单的 MVC 框架来展示工作,并可能在将来升级它。

我似乎不记得如何一起实现2个或更多视图,例如,这是控制器之一:

class Home extends Controller
{   

    public function index()
    {
        $model = new HomeModel;
        $result = $model->findAll();
        $data = $result;

        // Call the view
        $this->view('home', $data);
    }
}

但是我想构建这个主页,其中包含多个视图,例如:头部、侧边栏、表格、用户......所有不同的视图。

我尝试创建一个 renderView 函数,但没有这样做。

function renderView($viewName, $data) {
    // Your view rendering logic goes here
    // You might include the view file and pass data to it
    ob_start();
    include $viewName . '.php';
    return ob_get_clean();
}

我还检查了旧的 Magento 结构,但无法理解它(距离我上次尝试 PHP 已经过去 4 年了)

php model-view-controller templating
1个回答
0
投票

您想要做的事情可以通过将视图数组传递到您的函数中来完成(我省略了

$data
,因为它没有被使用:

function renderViews($viewNames) {
    // Your view rendering logic goes here
    // You might include the view file and pass data to it
    ob_start();
    foreach($viewNames as $viewName){
        include $viewName . '.php';
    }
    return ob_get_clean();
}

然后定义你的观点:

$viewNames = [];
$viewNames[0] = 'thisFile';
$viewNames[0] = 'thatFile';
$viewNames[0] = 'otherFile';

然后只需将数组传递给您的函数即可:

->renderViews($viewNames);
© www.soinside.com 2019 - 2024. All rights reserved.