2012-01-05 66 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