Redirects
Redirects provides an iterator over redirect rules stored in CSV format.
It is designed so we can keep straightforward URL migrations in a file rather than hard-coding them into router callbacks.
CSV format
Each row contains:
- the old URI
- the new URI
Example:
/about-us,/about
/product/1234,/product/widget-1234
/dir/nested/old-link,/other-dir/new-link,303
Loading redirects
We can construct the object with either a pathname or an SplFileObject:
use GT\Routing\Redirects;
$redirects = new Redirects("redirects.csv");
Applying redirects
BaseRouter::handleRedirects() checks the current request path against the redirect list and throws the appropriate HTTP redirect exception when it finds a match.
$router->handleRedirects($redirects, $request);
In practice we would usually do this before calling route().
The comparison is against the request path, so these rules should be written as path-to-path redirects rather than full URI strings with query components.
Redirect response code
The redirect status comes from RouterConfig::$redirectResponseCode.
Supported mappings are:
300=>HttpMultipleChoices301=>HttpMovedPermanently302=>HttpFound303=>HttpSeeOther304=>HttpNotModified307=>HttpTemporaryRedirect- any other configured value =>
HttpPermanentRedirect(308)
Iterating manually
Redirects implements Iterator, so we can inspect or transform the data before applying it:
foreach($redirects as $from => $to) {
echo "$from -> $to", PHP_EOL;
}
To increase simplicity of application routes, logic can be stored in path-mapped files rather than namespaced classes. Read about this in the logic stream wrapper section.