I’m working with PHPRO’s MVC framework and am having problems passing a Registry object to my controller class.
In my Router class, the loadController() method determines which controller to load and instantiates it. In the process, it passes the controller a Registry object that contains, among other things, a Template object:
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);
}
}
From Xdebug, I know that Router’s $registry property has everything it’s supposed to prior to being passed as an argument to Index’s constructor.
However, $registry fails to make it to Index intact. Here are the class definitions for Index and its parent Controller:
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');
}
}
With the code as shown, I get this error message: “Call to undefined method stdClass::show() in …Index.php”.
Within Index, Xdebug shows $registry as null, so I know it’s inheriting from the parent. But somewhere between the code to create a new Index object and the Index class definition, $registry gets lost.
While debugging, I found that eliminating the Controller class from the equation stops the error from occurring:
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');
}
}
Of course, this doesn’t really solve anything because I still need the Controller class, but hopefully it will help as a clue to the problem.
Can anyone see why I’m losing the contents of $registry when it gets passed to Index?
This should work :
In PHP the constructors are not inherited.
Aadditionally , you might benefit from watching this video and some other of the series : The Clean Code Talks – Don’t Look For Things! .