Beautifying URLs in PHP frameworks
P粉176980522
P粉176980522 2023-10-30 09:40:09
0
1
699

I know you can add rules in htaccess, but I found that PHP frameworks don't do that and somehow you still have beautiful URLs. How can servers do this if they don't know the URL rules?

I've been looking for Yii's url manager class, but I don't understand how it does it.

P粉176980522
P粉176980522

reply all(1)
P粉801904089

This is usually done by routing all requests to a single entry point (a file that executes different code based on the request), with the following rules:

# Redirect everything that doesn't match a directory or file to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php [L]

The file then compares the request($_SERVER["REQUEST_URI"]) with a list of routes - patterns that match the request to a controller action (in an MVC application) or other actions Map execution paths. Frameworks often include a route that can infer controllers and actions from the request itself, as a backup route.

A simple example:

<?php

// Define a couple of simple actions
class Home {
    public function GET() { return 'Homepage'; }
}

class About {
    public function GET() { return 'About page'; }
}

// Mapping of request pattern (URL) to action classes (above)
$routes = array(
    '/' => 'Home',
    '/about' => 'About'
);

// Match the request to a route (find the first matching URL in routes)
$request = '/' . trim($_SERVER['REQUEST_URI'], '/');
$route = null;
foreach ($routes as $pattern => $class) {
    if ($pattern == $request) {
        $route = $class;
        break;
    }
}

// If no route matched, or class for route not found (404)
if (is_null($route) || !class_exists($route)) {
    header('HTTP/1.1 404 Not Found');
    echo 'Page not found';
    exit(1);
}

// If method not found in action class, send a 405 (e.g. Home::POST())
if (!method_exists($route, $_SERVER["REQUEST_METHOD"])) {
    header('HTTP/1.1 405 Method not allowed');
    echo 'Method not allowed';
    exit(1);
}

// Otherwise, return the result of the action
$action = new $route;
$result = call_user_func(array($action, $_SERVER["REQUEST_METHOD"]));
echo $result;

In conjunction with the first configuration, this is a simple script that allows you to use URLs like domain.com/about. Hope this helps you understand what's going on here.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template