其他模块的 Phalcon 多模块路由

Phalcon multi module routes for other modules

我正在使用 Phalcon php。我必须尝试使用​​multi modules architecture。我有一个前端和后端。前端应用程序是默认模块。但是我对其他模块一无所知。如果我在后端有 50 个控制器,控制器有 10 个动作,我必须为后端模块定义所有路由?

我使用的场景与您相同。无需定义所有可能的路线。这是我的路线,它们对于我在 CMS 区域需要的任何东西都是通用的:

// Frontend routes
// ....

// CMS Routes
$router->add('/cms', [
         'module' => 'backend', 
         'controller' => 'admin', 
         'action' => 'login'
        ]);

$router->add('/cms/:controller/:action/([0-9]+)/:params', [
         'module' => 'backend',
         'controller' => 1,
         'action' => 2,
         'id' => 3, 
         'params' => 4
        ])->setName('backend-full');

$router->add('/cms/:controller/:action', [
         'module' => 'backend',
         'controller' => 1,
         'action' => 2
        ])->setName('backend-short');

$router->add('/cms/:controller', [
         'module' => 'backend',
         'controller' => 1,
         'action' => 'index'
       ]);

对于后端路由,您不必定义 50 多个不同的路由来匹配所有控制器/操作组合。您基本上可以坚持使用 Phalcon 提供的默认路由。

这是一个可能符合您需要的示例。我不确定您的确切项目结构是什么。但是从你提供的例子来看,试试这个:

$router = new Phalcon\Mvc\Router();

// set the defaults, so Phalcon knows where to start and where to fall back to
$router->setDefaultModule('frontend');
$router->setDefaultNamespace('Apps\Frontend\Controllers');
$router->setDefaultAction("index");
$router->setDefaultController("index");

$router->removeExtraSlashes(true);

/* ----------------------------------------------------- */
/* ------------------ FRONTEND ROUTES ------------------ */
/* ----------------------------------------------------- */

$router->add('/([a-zA-Z\-]+)/([a-zA-Z\-]+)/:params', [
    'module'     => 'frontend',
    'namespace'  => 'Apps\Frontend\Controllers',
    'controller' => 1,
    'action'     => 2,
    'params'     => 3
]);


/* ----------------------------------------------------- */
/* ------------------ BACKEND ROUTES ------------------- */
/* ----------------------------------------------------- */
// to keep your routes.php file clean,
// you can create a separate router group for your backend routes.

$backend = new Phalcon\Mvc\Router\Group();
$backend->setPrefix('/backend');

// for a backend route with a controller
$backend->add('/([a-zA-Z\-]+)', [
    'module'     => 'backend',
    'namespace'  => 'Apps\Backend\Controllers',
    'controller' => 1,
    'action'     => 'index'
]);

// for a backend route with a controller/action
$backend->add('/([a-zA-Z\-]+)/([a-zA-Z\-]+)', [
    'module'     => 'backend',
    'namespace'  => 'Apps\Backend\Controllers',
    'controller' => 1,
    'action'     => 2
]);

// for a backend route with a controller/action/parameter
$backend->add('/([a-zA-Z\-]+)/([a-zA-Z\-]+)/:params', [
    'module'     => 'backend',
    'namespace'  => 'Apps\Backend\Controllers',
    'controller' => 1,
    'action'     => 2,
    'params'     => 3
]);

// add your backend routes to the main router.
$router->mount($backend);