johnnietheblack johnnietheblack - 4 years ago 369
PHP Question

Simple PHP routing

I am setting up a simple routing system for my new custom MVC framework that I am making.

Currently my router class views the URL as such:

So, essentially...I've been reserving the first two segments of the URI for controller routing. However, what if I just want to run the following?

...which would attempt to just run the default controller action and send the extra parameters to it?

Here is the simple router I'm using:

\* --- htaccess --- *\
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

\* --- index.php --- *\
if (array_key_exists('rt',$_GET)) {
$path = $_GET['rt'];
$uri = explode('/',$this->path);
if(empty($uri[0])) {
elseif(empty($uri[1])) {
else {
else {

\* --- loader class --- *\
public function ctrl($ctrl,$action=null) {
$ctrl_name = 'Ctrl_'.ucfirst(strtolower($ctrl));
$ctrl_path = ABS_PATH . 'ctrl/' . strtolower($ctrl) . '.php';
if(file_exists($ctrl_path)) { require_once $ctrl_path;}

$ctrl = new $ctrl_name();

is_null($action) ? $action = "__default" : $action = strtolower($action);

How can I do this?

Answer Source

You could handle this within your controller. Typically, MVC frameworks will call a default method when the requested method isn't available. Simply overwrite this fallback-method to call your desired method and pass the parameter list in as parameters.

For instance, KohanaPHP has the __call($method, $params) method that is called when the requested method doesn't exist. You could handle the logic within this, or its functional equivalent in your MVC framework..

This would let you keep the logic internal to the controller itself rather than having it blasted out between various files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download