Monday, 12 August 2013

PHP MVC Routing -> How do I convert uri array elements to a string useful for routing?

PHP MVC Routing -> How do I convert uri array elements to a string useful
for routing?

Summary of Issues
I'm having some minor issues with my routing in an MVC framework that I am
making. The code looks like it should work, but somewhere there is
something wrong with the way I've split up the requested uri into an array
and assigned it to a string variable. I eliminated all of the errors that
originally popped up, so I moved on to instancialize the controller and
this is what I get:
Error Log
Class name must be a valid object or a string in
/home2/canforce/public_html/index.php on line 23
index.php
//analyze request
$request = new Request(); //breaks up the uri into an array
//routing
$router = new Router(array($request)); //routes the requested uri
$router->route();
//instancialize and execute the controller
$controller = new $router->getController();
$method = $router->getMethod();
$controller->$method();
Request.php
class Request {
public function __construct() {
//separates the uri into an array
$uri = explode('/',$_SERVER['REQUEST_URI']);
$uri = array_filter($uri);
//stores the requested controller from the uri
if($uri[0]!="") {
$request['controller'] = $uri[0];
}
else {
$request['controller'] = "home";//defaults to home
}
//stores the requested method from the uri
if(isset($uri[1])) {
$request['method'] = $uri[1];
}
else {
$request['method'] = "index";//defaults to index
}
//stores the requested arguments in array form
$count = count($uri);
$j=0;
for($i=2;$i<$count;$i++) {
$request['args'][j] = $request[i];
$j++;
}
return($request);
}
}
Router.php
class Router {
private $language = NULL;
private $controller;
private $view;
private $method;
private $args = NULL;
public function __construct($request) { //given the requested uri in array
form, stores it in local variables
$this->controller = $request['controller'];
$this->method = $request['method'];
$this->args = $request['args'];
}
public function route() { //put the requested uri into forms we can deal with
}
public function getLanguage() {
return $this->language;
}
public function getController() {
return $this->controller;
}
public function getView() {
return $this->view;
}
public function getMethod() {
return $this->method;
}
public function getArgs() {
return $this->args;
}
}


Any Help is Appreciated!

No comments:

Post a Comment