2012-01-05 12 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をから、私はそれは次のように渡される前にになっていますルータの$レジストリプロパティがすべてを持っていることを知っていますIndexのコンストラクタの引数。

ただし、$ registryはインデックスにそのまま反映されません。ここではインデックスとその親のコントローラのクラス定義です:示すように

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'); 
    } 
} 

のコードでは、私は、このエラーメッセージが表示されます:「未定義のメソッドはstdClassに呼び出し::ショーを()... index.phpの中で」 。

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'); 
    } 
} 

が、これは本当に何も解決しませんが、うまくいけばそれは問題の手がかりとして役立つでしょう。

インデックスに渡されたときに$ registryの内容が失われている理由は誰にも見えますか?

答えて

1

これは動作するはずです:PHPで

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

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

をコンストラクタは継承されません。

さらに、このビデオと他のシリーズのいくつかをご覧になることでメリットがあります。The Clean Code Talks - Don't Look For Things!

+0

偉大なリンクをありがとう - 私はそれをすでに3回見てきましたが、シリーズは私を大いに助けています。 – cantera

関連する問題