So, another in a series of posts where I package up some code I often use into a reusable library, let me introduce a simple PHP library for creating virtual pages.
Virtual pages are pages on a website that are generated in code, and are sent to the client’s browser, but don’t correspond directly to a physical file. This process requires mod_rewrite on Apache, but similar functionality exists in other web servers.
Defining your endpoint
You must specify your endpoint, and then a handling function. This function can be anything callable; functions, methods or an enclosure.
\simple_page_handler\Page::create('my/page/', function($page, array $subpages) { // Your page handling code });
Writing your endpoint handler
You then trigger the handled pages by writing a page handler, and then directing Apache to redirect unhandled requests to this endpoint.
Example endpoint:
try { if (!\simple_page_handler\Page::call(\simple_page_handler\Input::get('page'))) { \simple_page_handler\Page::set503(); echo "Something went wrong."; } } catch (Exception $e) { echo $e->getMessage(); }
And your redirect code:
# Redirect anything that isn't a real file to our example page handler RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ example_page_handler.php?page=$1 [QSA]
Hopefully this’ll be useful to someone!