Jump to content

URL Router Try/Catch Block


punk_runner

Recommended Posts

I have the code below working perfectly, but I was wondering if there is a more eloquent way to write this, specifically handling the exceptions...

 

This creates an object of a Router Class that parses my clean URLs into a Controller name, method name and the rest are arguments.

 

So for example: www.domain.com/users/view/profile/bobsmith would route to the Users Controller, and find the viewUsers

method and pass the arguments "profile" and "bobsmith" to it, and the method would take it from there... works great.

 

That explains what this code does. My only question is if there is a cleaner way to handle the exceptions, so I don't have

"throw new exception" written four times. Thoughts? Or is it good to go?

 

 

$rawURL = getPageURL();
$router = new Router($rawURL,$rootDIR);
$controller = $router->getController();
$method = $router->getMethod();
$arguments = $router->getArguments();

try {
// check controller exists and set controller path //
if ((isset($controller) && ($controller != ''))) {
	$controllerPath = APPLICATION_PATH . "controllers/" . $controller . ".class.php";

	// check controller path exists //
	if (file_exists($controllerPath)) {
		    
		// set method name and check method exists //
		if ((isset($method) && ($method != ''))) {
			$methodName = $method . ucfirst($controller);

			if (method_exists($controller, $methodName)) {
			// test it out //
				$test = new $controller();
				$response = $test->$methodName($arguments[0]);
				echo $response;
			}
			else {
				// method_exists failed //
				throw new Exception("That method does not exist foo!");
			}
		}
		else {
			// method was not found in URL //
			throw new Exception("No method name was given foo!");
		}
	}
	else {
		// file_exists failed //
		throw new Exception("That controller does not exist foo!");
	}
}
else {
	// controller was not found in URL //
	throw new Exception("No controller name was given foo!");
}
}
catch (Exception $e) {
// spit it out foo //
echo $e->getMessage();
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.