将变量从控制器传递到视图


passing variable from Controller to View

我有一个问题,我一直在制作自己的MVC应用程序,但在模型和控制器之间传递变量似乎有问题。控制器的输出是一个包含一些json格式数据的单个变量,看起来很简单。

控制器

<?php 
class controllerLib 
{
     function __construct() 
     {
            $this->view = new view();
     }
     public function getModel($model) 
     {
            $modelName = $model."Model"; 
            $this->model=new $modelName();
     }
}
 class controller extends controllerLib
 {
     function __construct()
     {
            parent::__construct();
     } 
     public function addresses($arg = false) 
     {
            echo'Addresses '.$arg.'<br />';
            $this->view->render('addressesView');
            $this->view->showAddresses = $this->model->getAddresses(); 
     }
 }
 ?>

查看

 <?php 
 class view
 {
    function __construct()
    {
    }
    public function render($plik)
    {
        $render = new $plik();
    }
 }
 class addressesView extends view
 {
    public $showAddresses;
    function __construct()
    {
        parent::__construct();
        require 'view/head.php';
        $result = $this->showAddresses;

        require 'view/foot.php';
    }
 }

 ?>

现在的问题是$this->showAddresses并没有传递到视图,我被卡住了。

代码有各种问题:

  1. render()将新视图保存在本地var中,这样在函数结束后就不存在了

  2. 不能期望$this->showAddresses在构造函数时具有值。

您应该将render()方法实现为View构造函数之外的方法。

function __construct() 
{
    parent::__construct();
    require 'view/head.php';
    $result = $this->showAddresses; // (NULL) The object is not created yet

    require 'view/foot.php';
}

视图类别:

public function factory($plik) // Old render($splik) method
{
    return new $plik();
}

地址查看类别:

function __construct() 
{
  parent::__construct();
}
function render()
{
    require 'view/head.php';
    $result = $this->showAddresses; // Object is created and the field has a value

    require 'view/foot.php';
}

控制器类别:

 $view = $this->view->factory('addressesView');
 $view->showAddresses = $this->model->getAddresses(); 
 $view->render();