'How to replace the id of a get paramete with his name instead in PHP?
Hello Stackoverflow community, I'm new using PHP and I have been trying to figure out how to make urls friendly to the user. This is what a I need to do:
Go from this:
http://localhost/myproject/categories/1
To this:
http://localhost/myproject/categories/{name of the category}
I currently using a simple Router class to handle my website entry point:
<?php
namespace CMS;
class Router
{
private array $handlers;
private $notFoundHandler;
private const METHOD_POST = 'POST';
private const METHOD_GET = 'GET';
public function get( string $path, $handler ): void
{
$this->addHandler(self::METHOD_GET, $path , $handler);
}
public function post( string $path, $handler ): void
{
$this->addHandler(self::METHOD_POST, $path , $handler);
}
public function addHandler( string $method, string $path, $handler ): void
{
$this->handlers[$method . $path] = [
'path' => $path,
'method' => $method,
'handler' => $handler
];
}
public function addNotFoundHandler($handler):void
{
$this->notFoundHandler = $handler;
}
public function run()
{
$requestUri = parse_url($_SERVER['REQUEST_URI']);
$requestPath = $requestUri['path'];
$method = $_SERVER['REQUEST_METHOD'];
$callback = null;
foreach ($this->handlers as $handler){
if($handler['path'] === $requestPath && $method === $handler['method']){
$callback = $handler['handler'];
}
}
if ( is_string($callback) ){
$parts = explode('::', $callback);
if ( is_array($parts) ){
$className = array_shift($parts);
$handler = new $className;
$method = array_shift($parts);
$callback = [$handler, $method];
}
}
if (!$callback) {
header("HTTP/1.0 404 Not Found");
if ( !empty($this->notFoundHandler) ) {
$callback = $this->notFoundHandler;
}
}
call_user_func_array($callback, [
array_merge($_GET, $_POST)
]);
}
}
An example of usage:
$router = new Router();
$router->get('/', function () {
echo "<a href='/categories?id=1'>Click Here</a>"; //Entry Test
});
$router->get('/categories', function ( array $params) {
echo 'Categories Page';
echo '<h1> Hello' . $params['id'] . '</h1>'; //This shows the id of the category
});
Please I need help:(, thank you!!
Solution 1:[1]
Finally I found a solution to my problem , I´m actually using a library calls Simple Router PHP. Here is the link: Simple-PHP-Router
It has good documentation for any router feature that you need. Have nice day.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Benjamin Flores |
