douzhi7754 2012-06-14 11:55
浏览 27
已采纳

DRY MVC视图/控制器分离

I have a custom MVC PHP framework that has a router class, which calls a controller, which uses a model, then the controller presents the view, etc etc.

My problem is that I can't figure out technically how to allow variables to pass between the controller and the view, semantically. I could do a quick-and-dirty fix, but what I want to have is this for a controller:

class IndexController extends Controller{
    var $name = "John"; // instance variable
}

And have this for a view:

<p> <?=$name?> </p>

My question is this:

  1. How can I create a Controller->render() function, or something similar, that allows the view to access instance variables from the controller? and,
  2. How can I do this without doing klutzy things like $data['view']['name'] = "John"; or having to write ten lines of code by default for any new controller I make. I want to do this so it's as DRY as possible.

Thanks.

Edit: FabioCosta's solution

I'm not sure I understand, so far I have my base controller like this:

<?php
    class Controller{
        public function __get($key){
            if(isset($this->$$key)) return $this->$$key;
        }
    }
?>

My base view class looks like this:

<?php
    class View{
         public $controller;
         public function render(){
         $this->controller = $this;
    }
?>

And I initialize from the router like this:

<?php
    $controller = new IndexController();
    $view = new IndexView();
    $view->render();
?>

However, this doesn't work, and I know I'm doing something wrong.

  • 写回答

2条回答 默认 最新

  • dongsuikai8286 2012-06-14 12:10
    关注

    Why not pass the controller that instantiates the view and use the __get magic method?

    like so:

      public function __get($key){
    
          if(isset($this->$key)) return $this->$key;
      }
    

    Here is a working example View.php:

    class View{
       protected $_controller;
       public function __construct(Controller $controller){
            $this->_controller=$controller;
       }
       public function render(){
            echo '<h1>Hello '.$this->_controller->name.'</h1>';
       }
    }
    

    Controller.php

    class Controller{
        protected $name='fabio';
        protected $_myView;
    
        public function __get($key){
    
            if(isset($this->$key)) return $this->$key;
       }
        public function __construct(){
            $this->_myView=new View($this);
        }
    
        public function indexAction(){
            $this->_myView->render();
        }
    }
    

    And the router:

    $c=new Controller();
    $c->indexAction();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大