2012-01-05 68 views
2

我正在与PHPRO's MVC framework一起工作,并且在将注册表对象传递给我的控制器类时遇到问题。PHP MVC:注册表失去了向控制器的方向

在我的路由器类中,loadController()方法确定要加载并实例化它的控制器。在这个过程中,它通过控制器登记对象,它包含,除其他事项外,模板对象:

class Router 
{ 
    private $registry;    // passed to Router's constructor 
    public $file;      // contains 'root/application/Index.php' 
    public $controller;    // contains 'Index' 

    public function loadController() 
    { 
     $this->getController();  // sets $this->file, $this->controller 
     include $this->file;   // loads Index controller class definition 
     $class = $this->controller; 
     $controller = new $class($this->registry); 
    } 
} 

从Xdebug的,我知道,路由器的$注册表属性的一切它应该之前作为一个被传递索引的构造函数的参数。

但是,$注册表未能使其保持索引不变。下面是指数及其母公司控制的类定义:如图所示

abstract class Controller 
{ 
    protected $registry; 

    function __construct($registry) 
    { 
     $this->registry = $registry; 
    } 
    abstract function index(); 
} 

class Index extends Controller 
{ 
    public function index() 
    { 
     $this->registry->template->welcome = 'Welcome'; 
     $this->registry->template->show('index'); 
    } 
} 

随着代码,我得到这个错误信息:“在......的index.php调用未定义的方法stdClass的::秀()” 。

在Index中,Xdebug显示$ registry为null,所以我知道它是从父级继承的。但是在创建新的Index对象和Index类定义的代码之间,$ registry会丢失。

调试时,我发现,消除方程Controller类发生停止错误:

class Index // extends Controller 
{ 
    private $registry; 

    function __construct($registry) 
    { 
     $this->registry = $registry; 
    } 

    public function index() 
    { 
     $this->registry->template->welcome = 'Welcome'; 
     $this->registry->template->show('index'); 
    } 
} 

当然,这并不能真正解决任何问题,因为我还需要Controller类,但希望这将有助于解决问题。

任何人都可以看到为什么我失去了$注册表的内容时,它传递给索引?

回答

1

这应该工作:

class Index extends Controller 
{ 
    public function __construct($registry) 
    { 
     parent::__construct($registry); 
    } 

    public function index() 
    { 
     $this->registry->template->welcome = 'Welcome'; 
     $this->registry->template->show('index'); 
    } 
} 

在PHP中的构造函数是不能继承的。

请注意,您可能会从观看此视频和其他一些系列中获益:The Clean Code Talks - Don't Look For Things!

+0

感谢您的好链接 - 我已经看过三次了,这个系列节目帮了我很多。 – cantera 2012-03-16 01:39:16