Answer the question
In order to leave comments, you need to log in
How to properly build PHP routing?
Hello,
As you understand from the title, I have only recently started to study programming and it is very important for me to understand how to write projects from scratch, and gain experience in the process of writing.
But I came to the issue of routing and got stuck. I had no experience writing websites even without CNC.
Tell me, please, about these moments:
1. I tried to write a router in this way
<?php
namespace library;
class Router {
function __construct(){
$uri = $_SERVER['REQUEST_URI'];
$uri = trim($uri,'/');
$uri = explode('/',$uri);
print_r($_GET);
echo $_GET[0];
echo '<br>';
if($uri[0] == ""){
$path = '\controller\IndexController';
$controller = new $path();
$method = 'dispatch';
$controller->$method();
}else{
$path = '\controller\IndexController';
$controller = new $path();
$method = 'dispatch';
if(!method_exists($controller,$method)){
}
$controller->$method();
}
}
public function getController(){
}
}
Answer the question
In order to leave comments, you need to log in
Look at the option that is provided in Symfony / Routing (not so much the implementation, but how routes are defined in general) and try to implement it in a similar way.
In essence, it all comes down to forming a regular expression from a rule. For example, a rule of the form
where route is our url template, and requirements - parameter validation (optional)
will generate a regular expression of the form:
where (?P<id>\d+)
is a named subpattern (you can do it easier, but it's more convenient). From version 5.2+ there may be options like this:
(?P<id>\d+)
(?<id>\d+)
(?'id'\d+)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question