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

时间:2016-08-01 07:41:56

标签: 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”,则前缀值应为false,因为cakephp 3默认为。
  4. 我试图从CakePHP 3文件中找到它。但我没有得到如何设置默认前缀。

    先谢谢

1 个答案:

答案 0 :(得分:4)

我自己回答了我的问题

我们必须通过爆炸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');
    });
}

因此主要技巧是需要在根作用域上传递前缀。