0

我有一个问题,我一直在制作自己的 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 没有传递给视图并且我卡住了。

4

1 回答 1

0

该代码有各种问题:

  1. render() 将新视图保存在本地变量中,以便函数结束后不存在

  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();
于 2012-09-11T07:54:12.350 回答