PHP code example of devcoder-xyz / php-router

1. Go to this page and download the library: Download devcoder-xyz/php-router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

devcoder-xyz / php-router example snippets



class IndexController {

    public function __invoke()
    {
        return 'Hello world!!';
    }
}

class ArticleController {

    public function getAll()
    {
        // db get all post
        return json_encode([
            ['id' => 1],
            ['id' => 2],
            ['id' => 3]
        ]);
    }

    public function get(int $id)
    {
        // db get post by id
        return json_encode(['id' => $id]);
    }

    public function put(int $id)
    {
        // db edited post by id
        return json_encode(['id' => $id]);
    }

    public function post()
    {
        // db create post
        return json_encode(['id' => 4]);
    }
}

// Define your routes
$routes = [
    new \PhpDevCommunity\Route('home_page', '/', [IndexController::class]),
    new \PhpDevCommunity\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),
    new \PhpDevCommunity\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),
];

// Initialize the router
$router = new \PhpDevCommunity\Router($routes, 'http://localhost');

try {
    // Match incoming request
    $route = $router->match(ServerRequestFactory::fromGlobals());
    
    // Handle the matched route
    $handler = $route->getHandler();
    $attributes = $route->getAttributes();
    $controllerName = $handler[0];
    $methodName = $handler[1] ?? null;
    $controller = new $controllerName();
    
    // Invoke the controller method
    if (!is_callable($controller)) {
        $controller =  [$controller, $methodName];
    }
    echo $controller(...array_values($attributes));

} catch (\PhpDevCommunity\Exception\MethodNotAllowed $exception) {
    header("HTTP/1.0 405 Method Not Allowed");
    exit();
} catch (\PhpDevCommunity\Exception\RouteNotFound $exception) {
    header("HTTP/1.0 404 Not Found");
    exit();
}

$route = new \PhpDevCommunity\Route('api_articles_post', '/api/articles', [ArticleController::class, 'post'], ['POST']);
$route = new \PhpDevCommunity\Route('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put'], ['PUT']);

/**
 * Creates a new GET route with the given name, path, and handler.
 *
 * @param string $name The name of the route.
 * @param string $path The path of the route.
 * @param mixed $handler The handler for the route.
 * @return BaseRoute The newly created GET route.
 */
public static function get(string $name, string $path, $handler): BaseRoute
{
    return new BaseRoute($name, $path, $handler);
}

$route = Route::get('home', '/', [HomeController::class, 'index']);

/**
 * Creates a new POST route with the given name, path, and handler.
 *
 * @param string $name The name of the route.
 * @param string $path The path of the route.
 * @param mixed $handler The handler for the route.
 * @return BaseRoute The newly created POST route.
 */
public static function post(string $name, string $path, $handler): BaseRoute
{
    return new BaseRoute($name, $path, $handler, ['POST']);
}

$route = Route::post('submit_form', '/submit', [FormController::class, 'submit']);

/**
 * Creates a new PUT route with the given name, path, and handler.
 *
 * @param string $name The name of the route.
 * @param string $path The path of the route.
 * @param mixed $handler The handler for the route.
 * @return BaseRoute The newly created PUT route.
 */
public static function put(string $name, string $path, $handler): BaseRoute
{
    return new BaseRoute($name, $path, $handler, ['PUT']);
}

$route = Route::put('update_item', '/item/{id}', [ItemController::class, 'update']);

/**
 * Creates a new DELETE route with the given name, path, and handler.
 *
 * @param string $name The name of the route.
 * @param string $path The path of the route.
 * @param mixed $handler The handler for the route.
 * @return BaseRoute The newly created DELETE route.
 */
public static function delete(string $name, string $path, $handler): BaseRoute
{
    return new BaseRoute($name, $path, $handler, ['DELETE']);
}

$route = Route::delete('delete_item', '/item/{id}', [ItemController::class, 'delete']);

/**
 * Sets a number constraint on the specified route parameters.
 *
 * @param mixed ...$parameters The route parameters to apply the constraint to.
 * @return self The updated Route instance.
 */
public function whereNumber(...$parameters): self
{
    $this->assignExprToParameters($parameters, '[0-9]+');
    return $this;
}

$route = (new Route('example', '/example/{id}'))->whereNumber('id');

/**
 * Sets a slug constraint on the specified route parameters.
 *
 * @param mixed ...$parameters The route parameters to apply the constraint to.
 * @return self The updated Route instance.
 */
public function whereSlug(...$parameters): self
{
    $this->assignExprToParameters($parameters, '[a-z0-9-]+');
    return $this;
}

$route = (new Route('article', '/article/{slug}'))->whereSlug('slug');

/**
 * Sets an alphanumeric constraint on the specified route parameters.
 *
 * @param mixed ...$parameters The route parameters to apply the constraint to.
 * @return self The updated Route instance.
 */
public function whereAlphaNumeric(...$parameters): self
{
    $this->assignExprToParameters($parameters, '[a-zA-Z0-9]+');
    return $this;
}

$route = (new Route('user', '/user/{username}'))->whereAlphaNumeric('username');

/**
 * Sets an alphabetic constraint on the specified route parameters.
 *
 * @param mixed ...$parameters The route parameters to apply the constraint to.
 * @return self The updated Route instance.
 */
public function whereAlpha(...$parameters): self
{
    $this->assignExprToParameters($parameters, '[a-zA-Z]+');
    return $this;
}

$route = (new Route('category', '/category/{name}'))->whereAlpha('name');

/**
 * Sets a custom constraint on the specified route parameter.
 *
 * @param string $parameter The route parameter to apply the constraint to.
 * @param string $expression The regular expression constraint.
 * @return self The updated Route instance.
 */
public function where(string $parameter, string $expression): self
{
    $this->wheres[$parameter] = $expression;
    return $this;
}

$route = (new Route('product', '/product/{code}'))->where('code', '\d{4}');

echo $router->generateUri('home_page'); // /
echo $router->generateUri('api_articles', ['id' => 1]); // /api/articles/1
echo $router->generateUri('api_articles', ['id' => 1], true); // http://localhost/api/articles/1

composer