/** * @param array $routes * @return MvcRouter */ public static function createFrom(array $routes) : MvcRouter { $router = new MvcRouter(false); $router->setUriSource(MvcRouter::URI_SOURCE_SERVER_REQUEST_URI); $router->removeExtraSlashes(true); foreach ($routes as $route) { $router->add($route['pattern'], $route['paths'] ?? null, $route['httpMethods'] ?? null, $route['position'] ?? MvcRouter::POSITION_LAST); } return $router; }
<?php /** * Created by PhpStorm. * User: vlad * Date: 8/28/15 * Time: 10:34 PM */ use Phalcon\Mvc\Router; $router = new Router(); $router->removeExtraSlashes(true); $router->add("/", array("controller" => "projects", "action" => "index")); $router->add("/projects(/?index)?", array("controller" => "static", "action" => "error")); $router->add("/404", array("controller" => "static", "action" => "error404")); $router->add("/403", array("controller" => "static", "action" => "error403")); $router->notFound(array("controller" => "static", "action" => "error404")); $router->handle();
/** * Initializes the router * * @param array $options */ protected function initRouter($options = array()) { $config = $this->di['config']; $this->di['router'] = function () use($config) { // Create the router without default routes (false) $router = new PhRouter(true); // 404 $router->notFound(array("controller" => "index", "action" => "notFound")); $router->removeExtraSlashes(true); foreach ($config['routes'] as $route => $items) { $router->add($route, $items->params->toArray())->setName($items->name); } return $router; }; }
<?php use Phalcon\Mvc\Router; /* ================================================== * ลงทะเบียน "เส้นทางเว็บแอพพลิเคชั่น" (Router) * Registering a router * ================================================== */ $config = $this->config; // Read the configuration $manager->set('router', function () use($config) { $router = new Router(); $router->setDefaultModule($config->router->moduleDefault); $router->setDefaultController($config->router->controllerDefault); $router->setDefaultAction($config->router->actionDefault); $router->removeExtraSlashes(TRUE); $addModule = explode(',', $config->module->moduleLists); foreach ($addModule as $module) { $pathModule = APPLICATION_PATH . '/modules/' . $module . '/Router.php'; $nameModule = ucfirst($module) . 'Router'; if (file_exists($pathModule)) { include_once $pathModule; $router->mount(new $nameModule($config)); } } return $router; });
public function diRouter() { $di = $this->getDI(); $cachePrefix = $this->getAppName(); $cacheFile = $this->getConfigPath() . "/_cache.{$cachePrefix}.router.php"; if ($router = $this->readCache($cacheFile, true)) { return $router; } $moduleManager = $di->getModuleManager(); $config = new Config(); $moduleName = ''; if ($moduleManager && ($modulesArray = $moduleManager->getModules())) { foreach ($modulesArray as $moduleName => $module) { //NOTICE: EvaEngine Load front-end router at last $config->merge(new Config($moduleManager->getModuleRoutesFrontend($moduleName))); $config->merge(new Config($moduleManager->getModuleRoutesBackend($moduleName))); } } //Disable default router $router = new Router(false); //Last extra slash $router->removeExtraSlashes(true); //Set last module as default module $router->setDefaultModule($moduleName); //NOTICE: Set a strange controller here to make router not match default index/index $router->setDefaultController('EvaEngineDefaultController'); $config = $config->toArray(); foreach ($config as $url => $route) { 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 Exception\RuntimeException(sprintf('No route pattern and paths found by route %s', $url)); } } else { $router->add($url, $route); } } if (!$di->getConfig()->debug) { $this->writeCache($cacheFile, $router, true); } else { //Dump merged routers for debug $this->writeCache($this->getConfigPath() . "/_debug.{$cachePrefix}.router.php", $router, true); } return $router; }
/** * * @param type $options */ protected function initRouter($options = []) { $this->_di->setShared('router', function () { $router = new Router(); $router->setDefaultModule('intranet'); $router->setDefaultNamespace('Intranet\\Controllers'); $router->removeExtraSlashes(true); return $router; }); }
/** * Sets the environment */ private function setupDI() { Di::reset(); $di = new Di(); $di->set('router', function () { $router = new Router(false); $router->add('/admin/:controller/p/:action', ['controller' => 1, 'action' => 2])->setName('adminProducts'); $router->add('/api/classes/{class}')->setName('classApi'); $router->add('/{year}/{month}/{title}')->setName('blogPost'); $router->add('/wiki/{article:[a-z]+}')->setName('wikipedia'); $router->add('/news/{country:[a-z]{2}}/([a-z+])/([a-z\\-+])/{page}', ['section' => 2, 'article' => 3])->setName('news'); $router->add('/([a-z]{2})/([a-zA-Z0-9_-]+)(/|)', ['lang' => 1, 'module' => 'main', 'controller' => 2, 'action' => 'index'])->setName('lang-controller'); $router->removeExtraSlashes(true); return $router; }); return $di; }
/** * Initializes the router * * @param array $options */ public function initRouter($options = []) { $config = $this->di['config']; $loader = $this->di['loader']; $this->di->setShared('router', function () use($config, $loader) { $router = new PhRouter(false); $router->setDefaultModule('common'); foreach ($config['app_routes'] as $route => $params) { $router->add($route, (array) $params)->setHostName($config->app_baseUri); } if (SUBDOMAIN == 'm') { $router->setDefaultModule('mobile'); $mobileRoutes = ['/:controller' => ['module' => 'mobile', 'controller' => 1], '/:controller/:action/:params' => ['module' => 'mobile', 'controller' => 1, 'action' => 2, 'params' => 3], '/' => ['module' => 'mobile', 'controller' => 'index', 'action' => 'index']]; foreach ($mobileRoutes as $route => $params) { $router->add($route, (array) $params)->setHostName('m.' . $config->app_baseUri); } } $router->removeExtraSlashes(true); return $router; }); }
public static function run(DiInterface $di, array $options = []) { $memoryUsage = memory_get_usage(); $currentTime = microtime(true); /** * The app path */ if (!defined('K_PATH')) { define('K_PATH', dirname(dirname(dirname(__FILE__)))); } /** * We will need the Utils class */ require_once K_PATH . '/library/Kitsune/Utils.php'; /** * Utils class */ $utils = new Utils(); $di->set('utils', $utils, true); /** * Check if this is a CLI app or not */ $cli = $utils->fetch($options, 'cli', false); if (!defined('K_CLI')) { define('K_CLI', $cli); } $tests = $utils->fetch($options, 'tests', false); if (!defined('K_TESTS')) { define('K_TESTS', $tests); } /** * The configuration is split into two different files. The first one * is the base configuration. The second one is machine/installation * specific. */ if (!file_exists(K_PATH . '/var/config/base.php')) { throw new \Exception('Base configuration files are missing'); } if (!file_exists(K_PATH . '/var/config/config.php')) { throw new \Exception('Configuration files are missing'); } /** * Get the config files and merge them */ $base = (require K_PATH . '/var/config/base.php'); $specific = (require K_PATH . '/var/config/config.php'); $combined = array_replace_recursive($base, $specific); $config = new Config($combined); $di->set('config', $config, true); $config = $di->get('config'); /** * Check if we are in debug/dev mode */ if (!defined('K_DEBUG')) { $debugMode = boolval($utils->fetch($config, 'debugMode', false)); define('K_DEBUG', $debugMode); } /** * Access to the debug/dev helper functions */ if (K_DEBUG) { require_once K_PATH . '/library/Kitsune/Debug.php'; } /** * We're a registering a set of directories taken from the * configuration file */ $loader = new Loader(); $loader->registerNamespaces($config->namespaces->toArray()); $loader->register(); require K_PATH . '/vendor/autoload.php'; /** * LOGGER * * The essential logging service */ $format = '[%date%][%type%] %message%'; $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log'; $logger = new LoggerFile($name); $formatter = new LoggerFormatter($format); $logger->setFormatter($formatter); $di->set('logger', $logger, true); /** * ERROR HANDLING */ ini_set('display_errors', boolval(K_DEBUG)); error_reporting(E_ALL); set_error_handler(function ($exception) use($logger) { if ($exception instanceof \Exception) { $logger->error($exception->__toString()); } else { $logger->error(json_encode(debug_backtrace())); } }); set_exception_handler(function (\Exception $exception) use($logger) { $logger->error($exception->getMessage()); }); register_shutdown_function(function () use($logger, $memoryUsage, $currentTime) { $memoryUsed = number_format((memory_get_usage() - $memoryUsage) / 1024, 3); $executionTime = number_format(microtime(true) - $currentTime, 4); if (K_DEBUG) { $logger->info('Shutdown completed [Memory: ' . $memoryUsed . 'Kb] ' . '[Execution: ' . $executionTime . ']'); } }); $timezone = $config->get('app_timezone', 'US/Eastern'); date_default_timezone_set($timezone); /** * Routes */ if (!K_CLI) { $di->set('router', function () use($config) { $router = new Router(false); $router->removeExtraSlashes(true); $routes = $config->routes->toArray(); foreach ($routes as $pattern => $options) { $router->add($pattern, $options); } return $router; }, true); } /** * We register the events manager */ $di->set('dispatcher', function () use($di) { $eventsManager = new EventsManager(); /** * Handle exceptions and not-found exceptions using NotFoundPlugin */ $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin()); $dispatcher = new Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace('Kitsune\\Controllers'); return $dispatcher; }); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlProvider(); $url->setBaseUri($config->baseUri); return $url; }); $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir(K_PATH . '/app/views/'); $view->registerEngines([".volt" => 'volt']); return $view; }); /** * Setting up volt */ $di->set('volt', function ($view, $di) { $volt = new VoltEngine($view, $di); $volt->setOptions(["compiledPath" => K_PATH . '/var/cache/volt/', 'stat' => K_DEBUG, 'compileAlways' => K_DEBUG]); return $volt; }, true); /** * Start the session the first time some component request the session * service */ $di->set('session', function () { $session = new SessionAdapter(); $session->start(); return $session; }); /** * Cache */ $frontConfig = $config->cache_data->front->toArray(); $backConfig = $config->cache_data->back->toArray(); $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter']; $frontCache = new $class($frontConfig['params']); $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter']; $cache = new $class($frontCache, $backConfig['params']); $di->set('cache', $cache, true); /** * viewCache */ $di->set('viewCache', function () use($config) { $frontConfig = $config->cache_view->front->toArray(); $backConfig = $config->cache_view->back->toArray(); $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter']; $frontCache = new $class($frontConfig['params']); $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter']; $cache = new $class($frontCache, $backConfig['params']); return $cache; }); /** * Markdown renderer */ $di->set('markdown', function () { $ciconia = new Ciconia(); $ciconia->addExtension(new FencedCodeBlockExtension()); $ciconia->addExtension(new TaskListExtension()); $ciconia->addExtension(new InlineStyleExtension()); $ciconia->addExtension(new WhiteSpaceExtension()); $ciconia->addExtension(new TableExtension()); $ciconia->addExtension(new UrlAutoLinkExtension()); $ciconia->addExtension(new MentionExtension()); $extension = new IssueExtension(); $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/issues/%s)'); $ciconia->addExtension($extension); $extension = new PullRequestExtension(); $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/pull/%s)'); $ciconia->addExtension($extension); return $ciconia; }, true); /** * Posts Finder */ $di->set('finder', function () use($utils, $cache) { $key = 'post.finder.cache'; $postFinder = $utils->cacheGet($key); if (null === $postFinder) { $postFinder = new PostFinder(); $cache->save($key, $postFinder); } return $postFinder; }, true); /** * For CLI I only need the dependency injector */ if (K_CLI) { return $di; } else { $application = new Application($di); if (K_TESTS) { return $application; } else { return $application->handle()->getContent(); } } }
public function run(DiInterface $diContainer, array $options = []) { $memoryUsage = memory_get_usage(); $currentTime = microtime(true); $this->diContainer = $diContainer; /** * The app path */ if (!defined('K_PATH')) { define('K_PATH', dirname(dirname(dirname(__FILE__)))); } /** * We will need the Utils class */ require_once K_PATH . '/library/Kitsune/Utils.php'; /** * Utils class */ $utils = new Utils(); $this->diContainer->set('utils', $utils, true); /** * Check if this is a CLI app or not */ $cli = $utils->fetch($options, 'cli', false); if (!defined('K_CLI')) { define('K_CLI', $cli); } $tests = $utils->fetch($options, 'tests', false); if (!defined('K_TESTS')) { define('K_TESTS', $tests); } /********************************************************************** * CONFIG **********************************************************************/ /** * The configuration is split into two different files. The first one * is the base configuration. The second one is machine/installation * specific. */ if (!file_exists(K_PATH . '/var/config/base.php')) { throw new \Exception('Base configuration files are missing'); } if (!file_exists(K_PATH . '/var/config/config.php')) { throw new \Exception('Configuration files are missing'); } /** * Get the config files and merge them */ $base = (require K_PATH . '/var/config/base.php'); $specific = (require K_PATH . '/var/config/config.php'); $combined = array_replace_recursive($base, $specific); $config = new Config($combined); $this->diContainer->set('config', $config, true); /** * Check if we are in debug/dev mode */ if (!defined('K_DEBUG')) { $debugMode = boolval($utils->fetch($config, 'debugMode', false)); define('K_DEBUG', $debugMode); } /** * Access to the debug/dev helper functions */ if (K_DEBUG) { require_once K_PATH . '/library/Kitsune/Debug.php'; } /********************************************************************** * LOADER **********************************************************************/ /** * We're a registering a set of directories taken from the * configuration file */ $loader = new Loader(); $loader->registerNamespaces($config->namespaces->toArray()); $loader->register(); require K_PATH . '/vendor/autoload.php'; /********************************************************************** * LOGGER **********************************************************************/ /** * The essential logging service */ $format = '[%date%][%type%] %message%'; $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log'; $logger = new LoggerFile($name); $formatter = new LoggerFormatter($format); $logger->setFormatter($formatter); $this->diContainer->set('logger', $logger, true); /********************************************************************** * ERROR HANDLING **********************************************************************/ ini_set('display_errors', boolval(K_DEBUG)); error_reporting(E_ALL); set_error_handler(function ($exception) use($logger) { if ($exception instanceof \Exception) { $logger->error($exception->__toString()); } else { $logger->error(json_encode(debug_backtrace())); } }); set_exception_handler(function (\Exception $exception) use($logger) { $logger->error($exception->getMessage()); }); register_shutdown_function(function () use($logger, $utils, $memoryUsage, $currentTime) { $memoryUsed = memory_get_usage() - $memoryUsage; $executionTime = microtime(true) - $currentTime; if (K_DEBUG) { $logger->info(sprintf('Shutdown completed [%s]s - [%s]', round($executionTime, 3), $utils->bytesToHuman($memoryUsed))); } }); $timezone = $config->get('app_timezone', 'US/Eastern'); date_default_timezone_set($timezone); /********************************************************************** * ROUTES **********************************************************************/ if (false === K_CLI) { $router = new Router(false); $router->removeExtraSlashes(true); $routes = $config->routes->toArray(); foreach ($routes as $pattern => $options) { $router->add($pattern, $options); } $this->diContainer->set('router', $router, true); } /********************************************************************** * DISPATCHER **********************************************************************/ if (false === K_CLI) { /** * We register the events manager */ $eventsManager = new EventsManager(); /** * Handle exceptions and not-found exceptions using NotFoundPlugin */ $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin()); $dispatcher = new Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace('Kitsune\\Controllers'); } else { $dispatcher = new PhCliDispatcher(); $dispatcher->setDefaultNamespace('Kitsune\\Cli\\Tasks'); } $this->diContainer->set('dispatcher', $dispatcher); /********************************************************************** * URL **********************************************************************/ /** * The URL component is used to generate all kind of urls in the application */ $url = new UrlProvider(); $url->setBaseUri($config->baseUri); $this->diContainer->set('url', $url); /********************************************************************** * VIEW **********************************************************************/ $view = new View(); $view->setViewsDir(K_PATH . '/app/views/'); $view->registerEngines([".volt" => function ($view) { return $this->setVoltOptions($view); }]); $this->diContainer->set('view', $view); /********************************************************************** * VIEW SIMPLE **********************************************************************/ $viewSimple = new ViewSimple(); $viewSimple->setViewsDir(K_PATH . '/app/views/'); $viewSimple->registerEngines([".volt" => function ($view) { return $this->setVoltOptions($view); }]); $this->diContainer->set('viewSimple', $viewSimple); /********************************************************************** * CACHE **********************************************************************/ $frontConfig = $config->cache_data->front->toArray(); $backConfig = $config->cache_data->back->toArray(); $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter']; $frontCache = new $class($frontConfig['params']); $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter']; $cache = new $class($frontCache, $backConfig['params']); $this->diContainer->set('cache', $cache, true); /********************************************************************** * POSTS FINDER **********************************************************************/ $this->diContainer->set('finder', new PostFinder(), true); /********************************************************************** * DISPATCH 17.5s **********************************************************************/ if (K_CLI) { return new PhCliConsole($this->diContainer); } else { $application = new Application($this->diContainer); if (K_TESTS) { return $application; } else { return $application->handle()->getContent(); } } }
/** * Initializes the router * * @param array $options */ protected function initRouter($options = array()) { $config = $this->di['config']; $this->di['router'] = function () use($config) { $router = new Router(false); $router->notFound(array('controller' => 'index', 'action' => 'notFound')); $router->removeExtraSlashes(true); foreach ($config['routes']->toArray() as $route => $items) { $route = $router->add($route, $items['params']); if (isset($items['name'])) { $route->setName($items['name']); } if (isset($items['via'])) { $route->via($items['via']); } if (isset($items['hostname'])) { $route->setHostname($items['hostname']); } } return $router; }; }
public function removeExtraSlashes($remove) { return parent::removeExtraSlashes($remove); }