model view controller - Parameters in Custom Router PHP -
i trying create custom router. have far:
<?php /** * created phpstorm. * user: antony * date: 5/30/16 * time: 3:31 pm */ namespace fab\router; class router { private $_geturi = array(); private $_getcontroller = array(); private $_getmethod = array(); private $_posturi = array(); private $_postcontroller = array(); private $_postmethod = array(); public function __construct() { } /** * build collection of internal urls * @param $uri - url user types in browser * @param $controller - controller handle url * @param $method - method of controller run */ public function get($uri, $controller, $method) { $this->_geturi[] = $uri; $this->_getcontroller[] = $controller; $this->_getmethod[] = $method; } /** * build collection of internal post urls * @param $uri - url user types in browser * @param $controller - controller handle url * @param $method - method of controller run */ public function post($uri, $controller, $method) { $this->_posturi[] = $uri; $this->_postcontroller[] = $controller; $this->_postmethod[] = $method; } public function submit() { if ($_server['request_method'] === 'get') { var_dump($_server['request_uri']); echo "\n"; $path = parse_url($_server['request_uri'], php_url_path); //get url var_dump($path); foreach ($this->_geturi $key => $value) { if (preg_match("#^$value$#", $path)) { // echo $key . ' => ' . $value; //see $path returns //instantiate controller $controller = 'fab\controllers\\' . $this->_getcontroller[$key]; $controller = new $controller(); //call appropriate method $method = $this->_getmethod[$key]; $controller->$method(); } } } elseif ($_server['request_method'] === 'post') { $path = parse_url($_server['request_uri'], php_url_path); //get url foreach ($this->_posturi $key => $value) { if (preg_match("#^$value$#", $path)) { //echo $key . ' => ' . $value; //see $path returns //instantiate controller $controller = 'fab\controllers\\' . $this->_postcontroller[$key]; $controller = new $controller(); //call appropriate method $method = $this->_postmethod[$key]; $controller->$method(); } } } } }
this allows me in index.php
like:
$router->get('/portfolio', 'maincontroller', 'portfolio');
what want create individual page every item in portfolio , give unique url. example, if have item 'dinosaur' in portfolio, want able say: $router->get('/portfolio/dinosaur', 'maincontroller', 'searchifdinosaurexistsindatabase');
so generally, have in index sth like: $router->get('/portfolio/{item}', 'maincontroller', 'searchindbforitem');
how can modify router in order achieve this?
you need add regular expression route. example (it's simple example):
$router->get('/portfolio/[\w\d]+', 'maincontroller', 'searchindbforitem');`
and need use preg_match
comparison route , url.
it's simple example of router https://github.com/newage/example/blob/master/core/route/httproute.php
Comments
Post a Comment