多模块(Multi Module)
多模块的应用使用了相同的文档根目录但拥有多个模块。在这种情况下,可以使用以下的文件目录结构:
multiple/ apps/ frontend/ controllers/ models/ views/ Module.php backend/ controllers/ models/ views/ Module.php public/ css/ img/ js/
在apps/下的 每一个目录 都有自己的MVC结构。Module.php文件代表了各个模块不同的配置,如自动加载器和自定义服务:
<?php namespace Multiple\Backend; use Phalcon\Loader; use Phalcon\Mvc\View; use Phalcon\DiInterface; use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\ModuleDefinitionInterface; class Module implements ModuleDefinitionInterface { /** * 注册自定义加载器 */ public function registerAutoloaders(DiInterface $di = null) { $loader = new Loader(); $loader->registerNamespaces( [ "Multiple\\Backend\\Controllers" => "../apps/backend/controllers/", "Multiple\\Backend\\Models" => "../apps/backend/models/", ] ); $loader->register(); } /** * 注册自定义服务 */ public function registerServices(DiInterface $di) { // Registering a dispatcher $di->set( "dispatcher", function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace("Multiple\\Backend\\Controllers"); return $dispatcher; } ); // Registering the view component $di->set( "view", function () { $view = new View(); $view->setViewsDir("../apps/backend/views/"); return $view; } ); } }
还需要一个指定的启动文件(通常是public/index.php)来加载多模块的MVC架构:
<?php use Phalcon\Mvc\Router; use Phalcon\Mvc\Application; use Phalcon\Di\FactoryDefault; $di = new FactoryDefault(); // 自定义路由 // More information how to set the router up https://docs.phalconphp.com/zh/latest/reference/routing.html $di->set( "router", function () { $router = new Router(); $router->setDefaultModule("frontend"); $router->add( "/login", [ "module" => "backend", "controller" => "login", "action" => "index", ] ); $router->add( "/admin/products/:action", [ "module" => "backend", "controller" => "products", "action" => 1, ] ); $router->add( "/products/:action", [ "controller" => "products", "action" => 1, ] ); return $router; } ); // 创建应用 $application = new Application($di); // 注册模块 $application->registerModules( [ "frontend" => [ "className" => "Multiple\\Frontend\\Module", "path" => "../apps/frontend/Module.php", ], "backend" => [ "className" => "Multiple\\Backend\\Module", "path" => "../apps/backend/Module.php", ] ] ); // 处理请求 $response = $application->handle(); $response->send(); } catch (\Exception $e) { echo $e->getMessage(); }