private function loadAnnotationRouter(RouteAnnotation $router) { $path = base_path('app/Controller'); $files = new Filesystem(); $controllers = $files->files($path); foreach ($controllers as $ctrl) { preg_match('/app\\/Controller\\/(.*)(Controller)\\.php/', $ctrl, $match); if ($match) { $resouce = "App\\Controller\\" . $match[1]; $router->addResource($resouce); } } }
/** * Creates a new instance of ApplicationRouter class and defines standard application routes * @param boolean $defaultRoutes */ public function __construct($defaultRoutes = false) { parent::__construct($defaultRoutes); $this->removeExtraSlashes(true); /** * Controller and action always default to 'index' */ $this->setDefaults(['controller' => 'index', 'action' => 'index']); /** * Add global matching route for the default module 'Backend': 'default-route' */ $this->add('/', ['module' => 'admin', 'namespace' => 'App\\Modules\\Admin\\Controllers\\'])->setName('default-route'); /** * Add default not found route */ $this->notFound(['controller' => 'index', 'action' => 'route404']); }
<?php use Phalcon\Mvc\Router\Annotations as RouterAnnotations; use Phalcon\Mvc\Router; $router = new RouterAnnotations(false); $router->notFound(["controller" => "Error", "action" => "error404"]); $router->add("/setlang/{lang}", array("controller" => "Manager", "action" => "setlanguage")); $router->add("/error404", array("controller" => "Error", "action" => "error404"))->setName("error404"); $router->addResource('Apartment', '/apartment'); $router->addResource('Tower', '/tower'); $router->addResource('Login', '/login'); $router->addResource('Country', '/country'); $router->addResource('State', '/state'); $router->addResource('City', '/city'); $router->addResource('Township', '/township'); $router->addResource('Neighborhood', '/neighborhood'); $router->addResource('Index', '/index'); $router->addResource('Test', '/test'); $router->addResource('Address', '/address'); $router->addResource('Error', '/error'); $router->addResource('User', '/user'); $router->addResource('Role', '/role'); $router->addResource('Action', '/action'); $router->addResource('UserRole', '/userrole'); $router->addResource('ActionRole', '/actionrole'); $router->addResource('Language', '/language'); $router->addResource('Translation', '/translation'); $router->addResource('Address', '/address'); $router->addResource('File', '/file'); $router->addResource('Gallery', '/gallery'); $router->addResource('SystemParameter', '/systemparameter');
/** * Init router. * * @param DI $di Dependency Injection. * @param Config $config Config object. * * @return Router */ protected function _initRouter($di, $config) { $cacheData = $di->get('cacheData'); $router = $cacheData->get(EnSystem::CACHE_KEY_ROUTER_DATA); if ($router == null) { $saveToCache = $router === null; // Load all controllers of all modules for routing system. $modules = $di->get('registry')->modules; // Use the annotations router. $router = new PhRouterAnnotations(false); $router->setDefaultModule(Application::SYSTEM_DEFAULT_MODULE); $router->setDefaultNamespace(ucfirst(Application::SYSTEM_DEFAULT_MODULE) . '\\Controller'); $router->setDefaultController('Index'); $router->setDefaultAction('index'); /** * Load all route from router file */ foreach ($modules as $module) { $moduleName = ucfirst($module); // Get all file names. $moduleDir = opendir($di->get('registry')->directories->modules . $moduleName . '/Controller'); while ($file = readdir($moduleDir)) { if ($file == "." || $file == ".." || strpos($file, 'Controller.php') === false) { continue; } $controller = $moduleName . '\\Controller\\' . str_replace('Controller.php', '', $file); $router->addModuleResource(strtolower($module), $controller); } closedir($moduleDir); } if ($saveToCache) { $cacheData->save(EnSystem::CACHE_KEY_ROUTER_DATA, $router, 2592000); // 30 days cache } } $router->removeExtraSlashes(true); $di->set('router', $router); return $router; }
public function testRouterFullResources() { $this->specify("The Annotations Router doesn't work properly", function ($uri, $method, $controller, $action, $params) { $router = new Annotations(false); $router->setDI($this->_getDI()); $router->addResource("Robots", "/"); $router->addResource("Products", "/products"); $router->addResource("About", "/about"); $router->handle("/products"); expect($router->getRoutes())->count(6); $router = new Annotations(false); $router->setDI($this->_getDI()); $router->addResource("Robots", "/"); $router->addResource("Products", "/products"); $router->addResource("About", "/about"); $router->handle("/about"); expect($router->getRoutes())->count(5); $router = new Annotations(false); $router->setDI($this->_getDI()); $router->setDefaultNamespace("MyNamespace\\Controllers"); $router->addResource("NamespacedAnnotation", "/namespaced"); $router->handle("/namespaced"); expect($router->getRoutes())->count(1); $router = new Annotations(false); $router->setDI($this->_getDI()); $router->addResource("MyNamespace\\Controllers\\NamespacedAnnotation", "/namespaced"); $router->handle("/namespaced/"); $router = new Annotations(false); $router->setDI($this->_getDI()); $router->addResource("Robots"); $router->addResource("Products"); $router->addResource("About"); $router->addResource("Main"); $router->handle(); expect($router->getRoutes())->count(9); $route = $router->getRouteByName("save-robot"); expect(is_object($route))->true(); expect($route)->isInstanceOf(Route::class); $route = $router->getRouteByName("save-product"); expect(is_object($route))->true(); expect($route)->isInstanceOf(Route::class); $_SERVER["REQUEST_METHOD"] = $method; $router->handle($uri); expect($router->getControllerName())->equals($controller); expect($router->getActionName())->equals($action); expect($router->getParams())->equals($params); expect($router->isExactControllerName())->true(); }, ['examples' => [["uri" => "/products/save", "method" => "PUT", "controller" => "products", "action" => "save", "params" => []], ["uri" => "/products/save", "method" => "POST", "controller" => "products", "action" => "save", "params" => []], ["uri" => "/products/edit/100", "method" => "GET", "controller" => "products", "action" => "edit", "params" => ["id" => "100"]], ["uri" => "/products", "method" => "GET", "controller" => "products", "action" => "index", "params" => []], ["uri" => "/robots/edit/100", "method" => "GET", "controller" => "robots", "action" => "edit", "params" => ["id" => "100"]], ["uri" => "/robots", "method" => "GET", "controller" => "robots", "action" => "index", "params" => []], ["uri" => "/robots/save", "method" => "PUT", "controller" => "robots", "action" => "save", "params" => []], ["uri" => "/about/team", "method" => "GET", "controller" => "about", "action" => "team", "params" => []], ["uri" => "/about/team", "method" => "POST", "controller" => "about", "action" => "teampost", "params" => []], ["uri" => "/", "method" => "GET", "controller" => "main", "action" => "index", "params" => []]]]); }
<?php use Phalcon\Mvc\Router\Annotations as RouterAnnotations; $router = new RouterAnnotations(false); // Read the annotations from ProductsController if the URI starts with /api/products $router->addResource('App\\Controllers\\Books', '/api/books'); return $router;
use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Router; use Phalcon\Mvc\Router\Annotations; use Phalcon\Mvc\Url as UrlResolver; use Phalcon\DI\FactoryDefault; use Phalcon\Session\Adapter\Files as SessionAdapter; /** * The FactoryDefault Dependency Injector automatically registers the right services to provide a full stack framework */ $di = new FactoryDefault(); /** * Registering a router */ $di['router'] = function () use(&$di) { $di['logger']->log('Init global router service '); $router = new Annotations(false); $router->setDefaultModule('admin'); // TODO Add specific route setting here // ARCH DO NOT REMOVE THIS LINE $router->addModuleResource('web', 'Wechat2\\Web\\Controllers\\Question', '/web/question'); $router->addModuleResource('web', 'Wechat2\\Web\\Controllers\\User', '/web/user'); $router->addModuleResource('wechat', 'Wechat2\\Wechat\\Controllers\\Server', '/wechat/server'); $router->addModuleResource('admin', 'Wechat2\\Admin\\Controllers\\Index', '/admin/index'); $router->addModuleResource('web', 'Wechat2\\Web\\Controllers\\Index', '/web/index'); $router->addModuleResource('wechat', 'Wechat2\\Wechat\\Controllers\\Index', '/wechat/index'); $router->addModuleResource('mobile', 'Wechat2\\Mobile\\Controllers\\Index', '/mobile/index'); return $router; }; /** * The URL component is used to generate all kinds of URLs in the application */
use Phalcon\Mvc\Router\Annotations; use Phalcon\Mvc\View; use Phalcon\Mvc\Url as UrlResolver; use Phalcon\Mvc\View\Engine\Volt as VoltEngine; use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter; use Phalcon\Session\Adapter\Files as SessionAdapter; use Phalcon\Flash\Direct as Flash; use Phalcon\Mvc\Dispatcher; $di = new FactoryDefault(); $di->set('dispatcher', function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace("QaApp\\Controllers"); return $dispatcher; }); $di->set('router', function () { $router = new Annotations(false); $router->removeExtraSlashes(true); //phalcon bug => fixed in 2.1.x //$router->setDefaultNamespace("QaApp\\Controllers"); $router->addResource("QaApp\\Controllers\\Question", '/v1/questions'); return $router; }); $di->setShared('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }); $di->setShared('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
use Rudder\MyValidation as Validation; /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new FactoryDefault(); /** * The URL component is used to generate all kind of urls in the application */ $di->setShared('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }); $di->setShared('router', function () use($di) { //Use the annotations router $router = new Router(false); //Read the resources from file require __DIR__ . '/routes.php'; // 路由事件拦截器 $eventsManager = $di->getShared('eventsManager'); $eventsManager->attach('router', new RouteListener(new logger('roter.log'))); $router->setEventsManager($eventsManager); return $router; }); /** * Setting up the view component */ $di->setShared('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
use Phalcon\Mvc\Application; use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Router\Annotations; use Phalcon\Mvc\View; $di = new \Phalcon\DI\FactoryDefault(); $di->set('view', function () { $view = new View(); $view->setViewsDir('../app/views/'); return $view; }); $di->set('annotations', function () { return new \Phalcon\Annotations\Adapter\Memory(); }); $di->set('router', function () { $router = new \Phalcon\Mvc\Router\Annotations(false); $router->removeExtraSlashes(true); $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); $router->addResource('Index', "/"); $router->addResource('User', "/user"); $router->addResource('OAuth', "/auth"); $router->notFound(["controller" => "index", "action" => "page404"]); return $router; }); $di->set('mongo', function () { $mongo = new MongoClient('mongodb://mongodb:27017'); return $mongo->selectDB("socwiz"); }, true); $di->set('collectionManager', function () { return new Phalcon\Mvc\Collection\Manager(); }, true);
/** * Init router. * * @param DI $di Dependency Injection. * @param Config $config Config object. * * @return Router */ protected function _initRouter($di, $config) { $defaultModuleName = ucfirst(Application::SYSTEM_DEFAULT_MODULE); // Check installation. if (!$config->installed) { $router = new RouterAnnotations(false); $router->setDefaultModule(Application::SYSTEM_DEFAULT_MODULE); $router->setDefaultNamespace($defaultModuleName . '\\Controller'); $router->setDefaultController("Install"); $router->setDefaultAction("index"); $router->addModuleResource(Application::SYSTEM_DEFAULT_MODULE, $defaultModuleName . '\\Controller\\Install'); $di->set('installationRequired', true); $di->set('router', $router); return; } $cacheData = $di->get('cacheData'); $router = $cacheData->get(System::CACHE_KEY_ROUTER_DATA); if ($config->application->debug || $router === null) { $saveToCache = $router === null; // Load all controllers of all modules for routing system. $modules = $di->get('registry')->modules; // Use the annotations router. $router = new RouterAnnotations(true); $router->setDefaultModule(Application::SYSTEM_DEFAULT_MODULE); $router->setDefaultNamespace(ucfirst(Application::SYSTEM_DEFAULT_MODULE) . '\\Controller'); $router->setDefaultController("Index"); $router->setDefaultAction("index"); // Read the annotations from controllers. foreach ($modules as $module) { $moduleName = ucfirst($module); // Get all file names. $files = scandir($di->get('registry')->directories->modules . $moduleName . '/Controller'); // Iterate files. foreach ($files as $file) { if ($file == "." || $file == ".." || strpos($file, 'Controller.php') === false) { continue; } $controller = $moduleName . '\\Controller\\' . str_replace('Controller.php', '', $file); $router->addModuleResource(strtolower($module), $controller); } } if ($saveToCache) { $cacheData->save(System::CACHE_KEY_ROUTER_DATA, $router, 2592000); // 30 days cache } } $di->set('router', $router); return $router; }
public function boot(Container $container) { // Pails 不使用Phalcon的Module功能,通过Namespace组织Controllers. // 如果出现多级,比如AdminApi,则一定要以Namespace的形式组织 Admin\Api\xxxxController // // Note: from phalcon 3, closure bind di as $this by default. so no use($app) needed. // $container->setShared('router', function () { // $router = new Annotations(false); $router->removeExtraSlashes(true); $router->setEventsManager($this->get('eventsManager')); $router->setDefaultNamespace('App\\Controllers'); $router->setDefaultController('application'); $router->setDefaultAction('index'); // Process /config/routes.php // Verb Path Action Route Name // GET /photo index photo.index // GET /photo/create create photo.create // POST /photo store photo.store // GET /photo/{photo} show photo.show // GET /photo/{photo}/edit edit photo.edit // PUT/PATCH /photo/{photo} update photo.update // DELETE /photo/{photo} destroy photo.destroy foreach ($this->getConfig('routes') as $url => $route) { // $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']; // // // a RESTful resource // if (isset($route['resource'])) { // if (!isset($route[''])) {} // foreach ($this->getResourceMethods($defaults, $options) as $m) { // $this->{'addResource'.ucfirst($m)}($url, $route, $options); // } // } else { // if (count($route) !== count($route, COUNT_RECURSIVE)) { // if (isset($route['pattern']) && isset($route['paths'])) { // $method = isset($route['httpMethods']) ? $route['httpMethods'] : null; // $router->add($route['pattern'], $route['paths'], $method); // } else { // throw new \RuntimeException(sprintf('No route pattern and paths found by route %s', $url)); // } // } else { // $router->add($url, $route); // } // } } // 定义注解路由 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path('Controllers')), \RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $item) { if (Text::endsWith($item, "Controller.php", false)) { $name = str_replace([$this->path('Controllers') . DIRECTORY_SEPARATOR, "Controller.php"], "", $item); $name = str_replace(DIRECTORY_SEPARATOR, "\\", $name); $router->addResource('App\\Controllers\\' . $name); } } // 定义404路由 $router->notFound(["controller" => "application", "action" => "notfound"]); // return $router; }); }