Variable Prefixed Routing in CakePHP

I'm creating an app in CakePHP which requires me to run 'multiple' apps within one CakePHP installation. Something like I have n controllers that behave the same for all applications, but they only differ when I call the database - anyway, I need to create a route which behaves something like this:

/app1/controller/action/a/b/c
/app2/controller/action/a/b/c

(where app1 and app2 are alphanumeric strings that can change to anything)

That would be routed to something like:

/controller/action/app1/a/b/c
(or the same for app2, and so on)

The routed route could be just /controller/action/a/b/c too, but I need to have a way to access the app1 / app2 parts of the URL within the controller (for further processing within the controller). Is there a way to do this in CakePHP? Thanks.

Slightly related question: When the above is accomplished, is there a way to set a 'default' app-name (like when I attempt to access /controller/action/a/b/c it will automatically be routed to the equivalent of typing /global/controller/action/a/b/c?)

Thanks!

Effectively: What I want is just to use Routing (or any other CakePHP 'method' that can do this) to handle URLs like /foobar/controller/action/the/rest to /controller/action/the/rest and pass "foobar" to the controller, somehow. "Foobar" is any alphanumeric string.

Answer #1:

In app/Config/routes.php add:

Router::connect( 
    '/:app/:controller/:action/*', 
    array(), 
    array( 'pass' => array( 'app' ))
);

This will pass the value of app as the first argument to the action in your controller. So in your controller you would do something like:

class FoosController Extends AppController {
    public function view_something($app, $a, $b, $c) { 
        // ...
    }
}

When you request /myApp1/foos/view_something/1/2/3 the value of $app would be 'myApp1', the value of $a would be 1, etc.

To connect other routes, before the above, you can add something like:

Router::connect(
    '/pages/:action/*',
    array( 'app' => 'global', 'controller' => 'pages' ),
    array( 'pass' => array( 'app' )) // to make app 1st arg in controller
);
Answered By: Jimmie Lin

Answer #2:

Instead of routing, you should use Model attribute -> dbconfig to change the databases dynamically. Also you should also have to send some arguments to the method by which you can identify which database needs to be connected with your application.

Answered By: Doug Owings
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles