基于子域在 CakePHP 3 中设置默认前缀

Har*_*dja 1 php cakephp cakephp-3.0

我想建立多个指向相同的 CakePHP v3 源代码的子域

情景是

  1. 如果域为“admin.localhost.com”,则前缀值应为 admin。
  2. 如果域是“xyz.localhost.com”、'abc.localhost.com' 或任何子域,则前缀值应为供应商
  3. 如果域是“localhost.com”或“www.localhost.com”,那么前缀值应该是假的,因为 cakephp 3 默认有。

我已经尝试从 CakePHP 3 文档中找出答案。但我不知道如何设置默认前缀。

提前致谢

Har*_*dja 5

我自己得到了我的问题的答案

我们必须config/routs.php通过爆炸来设置前缀HTTP_HOST

$exp_domain= explode(".",env("HTTP_HOST"));

$default_prefix=false; // default prefix is false
if(count($exp_domain)>2 && $exp_domain[0]!="www")
{
    if($exp_domain[0]=="admin") $default_prefix="admin"; 
    else $default_prefix="vendor";
}

if($default_prefix=="admin")
{
    // default routes  for vendor users with base scope and pass prefix as admin ($default_prefix)
    Router::scope('/', function ($routes) use($default_prefix) {
        $routes->connect('/', ['controller' => 'admins', 'action' => 'dashboard','prefix'=>$default_prefix]);
        $routes->connect('/:action', ['controller' => 'admins','prefix'=>$default_prefix]);
        $routes->connect('/:controller/:action', ['controller' => 'controller', 'action' => 'action','prefix'=>$default_prefix]);
        $routes->connect('/:controller/:action/*', ['controller' => 'controller', 'action' => 'action','prefix'=>$default_prefix]);

    });

}
else if($default_prefix=="vendor")
{
    // default routes  for vendor users with base scope and pass prefix as vendor ($default_prefix)
    Router::scope('/', function ($routes) use($default_prefix) {
        $routes->connect('/', ['controller' => 'vendors', 'action' => 'dashboard','prefix'=>$default_prefix]);
        $routes->connect('/:action', ['controller' => 'vendors','prefix'=>$default_prefix]);
        $routes->connect('/:controller/:action', ['controller' => 'controller', 'action' => 'action','prefix'=>$default_prefix]);
        $routes->connect('/:controller/:action/*', ['controller' => 'controller', 'action' => 'action','prefix'=>$default_prefix]);
    });
}
else
{
    // default routes  for normal users with base scope
    Router::scope('/', function ($routes) use($default_prefix) {
        $routes->connect('/', ['controller' => 'users', 'action' => 'dashboard');
        $routes->connect('/:action', ['controller' => 'users');
        $routes->connect('/:controller/:action', ['controller' => 'controller', 'action' => 'action');
        $routes->connect('/:controller/:action/*', ['controller' => 'controller', 'action' => 'action');
    });
}
Run Code Online (Sandbox Code Playgroud)

所以主要技巧是需要在根范围内传递前缀。