I’m writing a custom MVC framework for a PHP project and everything is great until it comes to getting arguments from the URL route. I’m stuck on passing parts of the URL route into a function argument dynamically. I already have a method which is just to implode the route and use the array for the function arguments but I would really like to know how to do it like in CodeIgnitor or CakePHP.
Here’s what i want to have done. The site url would be…
url: http://yoursite.com/edit/35
url: http://yoursite.com/edit/35/foo
<?php
use AppServicesRoute;
use AppMiddleware{
Auth,
Guest
};
Route::get('register','RegisterController','index',[Guest::class]);
Route::post('submit-register','RegisterController','register',[Guest::class]);
Route::get('edit/1','RegisterController','editUser',[Auth::class]);
Route::get('edit/1/amol','RegisterController','editUser',[Auth::class])
In my service/route.php file as follow :
<?php
namespace AppServices;
class Route{
private static $routes = [];
private static $controllerNamespace = 'AppControllers\';
public static function add($uri, $controller,$action, $method='GET',$middleware=[])
{
self::$routes[] = [
'method'=> $method,
'uri'=> $uri,
'controller'=> $controller,
'action'=> $action,
'middleware' => $middleware
];
}
public static function get($uri, $controller,$action,$middleware=[]){
self::add($uri,$controller,$action,'GET',$middleware);
}
public static function post($uri, $controller,$action,$middleware=[]){
self::add($uri,$controller,$action,'POST',$middleware);
}
public static function handle(){
$requestURI = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];
foreach(self::$routes as $route){
if('/'.$route['uri'] === $requestURI && $route['method'] == $requestMethod){
// handle middleware
foreach($route['middleware'] as $middleware){
$middlewareClass = new $middleware;
$middlewareClass->handle();
}
$controllerClass = self::$controllerNamespace.$route['controller'];
$action = $route['action'];
$controller = new $controllerClass();
$controller->$action();
return;
}
}
echo '404 - page not found';
}
}
And my register post controller as follows :
class RegisterController{
public function index(){
view('auth.register');
}
public function register(){
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user = new User;
$user->name = $_POST['name'];
$user->email = $_POST['email'];
$user->password = $_POST['password'];
if($user->register()){
echo 'user registered';
}else{
echo 'Unable to register user';
}
}
}
}
Now i have issue how to Use GET method with parameters and that parameters should be get in Controller method.I would really like to know how this is done. Thanks a lot!
Praful Rambade is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.