this is my first attemp to create a frontController and I’ve come over some little problem.
First let me give you an impression how my site looks like:
When I open http://mysite.com/test in my browser, the server will call an index.php with the GET parameter $controller (test). This is done by a .htaccess.
In the index.php there shall be created an instance of the class $controller.
For this I use the __autoload function of PHP.
So the code looks like this:
$controller = $_GET["controller"];
function __autoload($controller)
{
include("controllers/$controller.php");
if(!class_exists($controller, false))
{
eval
('
class '. $controller . '
{
public function __construct()
{
include("404.html");
exit();
}
}
');
}
}
$application = new $controller;
When you looked at the code I provided you may have noticed the eval() thingy in it.
I use this to avoid the fatal error when a $controller class doesn’t exist, and display a 404 instead of it.
And here starts the fun: when somebody enters an url like
There will be
Parse error: syntax error, unexpected ‘!’
And…
Fatal error: Class ‘ImATroll!:D’ not found
So the question is: How can I catch this? How can I escape the $controller variable a way that it only contains characters allowed for classnames?
You can actually just throw an exception from your autoload function (p.s.: use spl_autoload_register instead).
This exception is catchable, so you can provide the ‘default’ functionality.
This is by far the superior method, but if you insist on creating this fake controller, you should be using class_alias instead.