Variable Prefixed Routing in CakePHP

假如想象 提交于 2019-12-02 03:29:02

问题


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.


回答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
);



回答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.



来源:https://stackoverflow.com/questions/11463716/variable-prefixed-routing-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!