I'm trying to create a MVC Framework for studying purposes.
So, I'm trying to call the right class and action by reading URL. But, I'm getting troubles with call_user_func
function.
I have already read URL, and set controller and action names, but I can't call it. When I run call_user_func
function I get the following error: Fatal error: Class 'PageController' not found in...
Obviously the class is not loaded, and that's my question. How can I make it callable here? I have a namespace for it, but I don't know if it is useful for something.
Here's the code
namespace Core\Dispatcher;
use Core\Routing\Router;
class Dispatch {
private $params = [];
public function dispatch()
{
$this->getParams();
/*error occurs here*/ call_user_func(new $this->params['Controller'], $this->params['Action']);
}
private function getParams()
{
$this->params = Router::read();
}
}
/*
* Router::read reads url and return an array with Controller and Action names
*/
Yes, the whole thing is based on CakePHP Framework, but only class names, folders, etc.
So, any idea? I'm forgetting information?
Thank you
Edit Here's a link to my repo on Bitbucket. I think it's enable download. Bitbucket
The signature of call_user_func is:
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
param 1 is the callable
param 2..n are the parameters
So what you do here is, trying to call an object itself, with the action as parameter. That cannot work.
In order to call an object function, callable must be in format
array($object, $method)
So in your example:
call_user_func(array(new $this->params['Controller'], $this->params['Action']));
If your controller is in namespace App\Controller, then $this->params['Controller'] must have the value App\Controller\ClassName.
Also, you need to include the corresponding php file with the class definition, unless you have autoloading in place.