laracasts / The-PHP-Practitioner-Full-Source-Code

https://laracasts.com/series/php-for-beginners
177 stars 71 forks source link

How to pass a parameter to the router? #1

Open drpshtiwan opened 7 years ago

drpshtiwan commented 7 years ago

I know the the framework that created at the end of the course is small and simple but i looked at the routing system of it and noticed there is no way to pass a parameter to the controller. Mr.Jeffry can you explain how to pass a parameter to the router? like Laravel Routing $router->get('about/{name}', 'PagesController@about');

Thanks

davidavsira commented 7 years ago

Hi, Here is what you need to do. (not sure if its the best way to make it work, but it works.)

on you Router.php file change the method "direct" to this: if (array_key_exists($uri, $this->routes[$requestType])) { return $this->callAction( ...explode('@', $this->routes[$requestType][$uri]) ); }else{ foreach ($this->routes[$requestType] as $key => $val){ $pattern = preg_replace('#\(/\)#', '/?', $key); $pattern = "@^" .preg_replace('/{([a-zA-Z0-9\_\-]+)}/', '(?<$1>[a-zA-Z0-9\_\-]+)', $pattern). "$@D"; preg_match($pattern, $uri, $matches); array_shift($matches); if($matches){ $getAction = explode('@', $val); return $this->callAction($getAction[0], $getAction[1], $matches); } } } throw new Exception('No route defined for this URI.');

now add to "callAction" method the vars parameter and add it to the return action (I've also added default of empty array to the parameter so no errors given when trying to get to routes without vars) protected function callAction($controller, $action, $vars = []) // add $vars = [] in case $vars is empty { $controller = "App\\Controllers\\{$controller}"; $controller = new $controller; if (! method_exists($controller, $action)) { throw new Exception( "{$controller} does not respond to the {$action} action." ); } return $controller->$action($vars); // return $vars to the action }

now your routes file should look like this: $router->get('test/{id}', 'TestController@Test');

don't forget to add the vars parameter to the method "Test" on "TestController" (for example)

class TestController { public function Test($vars) { // you can get the var both ways: var_dump($vars['id']); var_dump($vars[0]); // or you can extract $vars and print each var from the url like $id for example. extract($vars); var_dump($id); } }

again, not sure how good its performance but it works.