/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = array('session', 'config', 'loader', 'url', 'router', 'view', 'cache', 'markdown'); foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}(); } $application = new PhApplication(); $application->setDI($this->di); return $application->handle($_SERVER['REQUEST_URI'])->getContent(); }
/** * @param array $config 配置文件 */ public function run(array $config) { $this->di = new FactoryDefault(); $this->app = new Application(); if (defined('APP_ENV') && APP_ENV == 'product') { $this->debug = false; error_reporting(0); } else { $this->debug = true; error_reporting(E_ALL); } $this->initConfig($config); try { $this->onBefore(); $this->initRouters(); $this->initUrl(); $this->initView(); $this->initDatabase(); $this->initModelsMetadata(); $this->initCookie(); $this->initCrypt(); $this->initLogger(); $this->onAfter(); $this->app->setDI($this->di); $this->registerModules(); echo $this->app->handle()->getContent(); } catch (\Exception $e) { echo $e->getMessage(); } }
public function testTestCase() { /** * ------ NOTE * Because i have no more time, only write one test for register motorbike * and do not test authentication and other parts */ $this->autheticate(); $_SERVER["REQUEST_METHOD"] = 'POST'; $_POST["brand"] = "Honda"; $_POST["model"] = "CB1100"; $_POST["cc"] = 250; $_POST["color"] = "black"; $_POST["weight"] = 750; $_POST["price"] = 78000000.0; $_POST["csrf"] = $this->handleCsrf(); $fh = fopen($this->di->get('config')->application->testsDir . "tempdata/honda-motorcycle", 'r'); $tmpfname = tempnam(sys_get_temp_dir(), "img"); $handle = fopen($tmpfname, "w"); fwrite($handle, fread($fh, 636958)); fclose($handle); fclose($fh); $_FILES["image"] = array("name" => "honda-motorcycles-cb1100.jpg", "type" => "image/jpeg", "tmp_name" => $tmpfname, "error" => "0", "size" => "636958"); $_SERVER["REQUEST_URI"] = "/motorbikes/create"; $_GET["_url"] = "/motorbikes/create"; $request = new Request(); $this->di->set('request', $request); $application = new Application($this->di); $files = $request->getUploadedFiles(); $result = $application->handle()->getContent(); $this->assertNotFalse(strpos($result, 'motorbike was created successfully'), 'Error in creating motorbike'); }
protected function load($uri, $method = "GET", $params = []) { $_SERVER['REQUEST_METHOD'] = $method; $_SERVER['REQUEST_URI'] = $uri; switch ($method) { case "GET": $_GET = $params; $_REQUEST = array_merge($_REQUEST, $_GET); break; case "POST": $_POST = $params; $_REQUEST = array_merge($_REQUEST, $_POST); break; case "PUT": $_PUT = $params; $_REQUEST = array_merge($_REQUEST, $_PUT); break; default: $_REQUEST = $params; break; } foreach ($params as $paramkey => $paramValue) { $this->getDi()->get('dispatcher')->setParam($paramkey, $paramValue); } $application = new Application($this->getDI()); $_GET['_url'] = $uri; $response = $application->handle(); return json_decode($response->getContent(), true); }
public function handle($uri = null) { /** @var Response $response */ $response = parent::handle($uri); if ($response->getContent()) { return $response; } switch ($response->getStatusCode()) { case Response::HTTP_NOT_FOUND: case Response::HTTP_METHOD_NOT_ALLOWED: case Response::HTTP_UNAUTHORIZED: case Response::HTTP_FORBIDDEN: case Response::HTTP_INTERNAL_SERVER_ERROR: if ($this->request->isAjax() || $this->request->isJson() || $response instanceof JsonResponse) { $response->setContent(['error' => $response->getStatusMessage()]); } else { $template = new Template($this->view, 'error'); $template->set('code', $response->getStatusCode()); $template->set('message', $response->getStatusMessage()); $response->setContent($template->render()); } break; default: break; } return $response; }
/** * @expectedException \Phalcon\Mvc\Dispatcher\Exception */ public function testApplicationWithNotFoundRoute() { $appKernel = new TestKernel('dev'); $appKernel->boot(); $application = new Application($appKernel->getDI()); ob_end_clean(); // application don't close output buffer after exception $application->handle('/asdasd111'); }
public function run($args = array()) { parent::run($args); // initialize our benchmarks $this->di['util']->startBenchmark(); // create the mvc application $application = new Application($this->di); // run auth init $this->di['auth']->init(); // output the content. our benchmark is finished in the base // controller before output is sent. echo $application->handle()->getContent(); }
/** * @param array $arguments * @throws */ public function run($arguments = array()) { $this->autoLoader(); $this->commonServices(); $this->customServices(); if ($this->mode === 'CLI') { if (empty($arguments)) { throw new \Exception('CLI Require Arguments'); } $this->application->handle($arguments); } else { echo $this->application->handle()->getContent(); } }
/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = array('session', 'config', 'loader', 'url', 'router', 'view', 'cache'); foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}(); } $application = new PhApplication(); $application->setDI($this->di); if (PHP_OS == 'Linux') { $uri = $_SERVER['REQUEST_URI']; } else { $uri = null; } return $application->handle($uri)->getContent(); }
/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = array('config', 'session', 'loader', 'url', 'router', 'database', 'view', 'cache', 'log', 'utils', 'debug'); try { // Handing missing controller errors $this->di->set('dispatcher', function () { //Create an EventsManager $eventsManager = new EventsManager(); // Attach a listener $eventsManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) { // Handle 404 exceptions if ($exception instanceof DispatchException) { $dispatcher->forward(array('controller' => 'index', 'action' => 'internalServerError')); return false; } // Alternative way, controller or action doesn't exist if ($event->getType() == 'beforeException') { switch ($exception->getCode()) { case \Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: case \Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND: $dispatcher->forward(array('controller' => 'index', 'action' => 'internalServerError')); return false; } } }); // Instantiate the Security plugin $security = new Security($di); // Listen for events produced in the dispatcher using the Security plugin $eventsManager->attach('dispatch', $security); $dispatcher = new \Phalcon\Mvc\Dispatcher(); // Bind the EventsManager to the dispatcher $dispatcher->setEventsManager($eventsManager); return $dispatcher; }, true); foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}(); } $application = new PhApplication(); $application->setDI($this->di); return $application->handle()->getContent(); } catch (PhException $e) { echo $e->getMessage(); } catch (\PDOException $e) { echo $e->getMessage(); } }
/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = array('session', 'config', 'loader', 'url', 'router', 'view', 'cache'); try { foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}(); } $application = new PhApplication(); $application->setDI($this->di); return $application->handle()->getContent(); } catch (PhException $e) { echo $e->getMessage(); } catch (\PDOException $e) { echo $e->getMessage(); } }
/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = array('config', 'loader', 'environment', 'timezone', 'debug', 'flash', 'url', 'dispatcher', 'view', 'logger', 'database', 'session', 'cache', 'behaviors'); try { foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}($options); } $application = new PhApplication(); $application->setDI($this->_di); return $application->handle()->getContent(); } catch (PhException $e) { echo $e->getMessage(); } catch (\PDOException $e) { echo $e->getMessage(); } }
/** * 开始运行 */ public function run() { try { $this->onBefore(); $this->initLoader(); $this->initRouters(); $this->initUrl(); $this->initDatabase(); $this->initModelsMetadata(); $this->initCookie(); $this->initLogger(); $this->initShortFunc(); \Phalcon\Mvc\Model::setup(['notNullValidations' => false]); $this->onAfter(); $this->app->setDI($this->di); $this->registerModules(); echo $this->app->handle()->getContent(); } catch (\Exception $e) { echo $e->getMessage(); } }
<?php use Phalcon\Mvc\Application; /** * Handle the request */ $application = new \Phalcon\Mvc\Application($di); /** * Register application modules */ if (isset($modules) && !empty($modules)) { $application->registerModules($modules); } echo $application->handle()->getContent();
$crypt = new Crypt(); $crypt->setKey($config->crypt->key); return $crypt; }); $di->setShared('redis', function () use($config) { $redis = new Redis(); $redis->open($config->redis->host, $config->redis->port); return $redis; }); $di->setShared('session', function () { $session = new RedisSessionAdapter(array('path' => 'tcp://127.0.0.1:6379?weight=1')); $session->start(); return $session; }); $di->set('router', function () { $router = new Router(); $router->add("/:controller/:action/:params", array('module' => 'frontend', 'controller' => 1, 'action' => 2, 'params' => 3)); $router->add("/admin/:controller/:action/:params", array('module' => 'backend', 'controller' => 1, 'action' => 2, 'params' => 3)); $router->add("/:controller/([a-z0-9:/+]+)/page:([0-9]+)", array('module' => 'frontend', 'controller' => 1, 'action' => 'index', 'params' => 2, 'page' => 3)); $router->add("/:controller/([0-9]+)", array('module' => 'frontend', 'controller' => 1, 'action' => 'detail', 'id' => 2)); $router->add("/", array('module' => 'frontend', 'controller' => 'index', 'action' => 'index')); return $router; }); try { $app = new Application($di); $app->registerModules(array('frontend' => array('className' => 'Pohome\\Frontend\\Module', 'path' => '../apps/frontend/Module.php'), 'backend' => array('className' => 'Pohome\\Backend\\Module', 'path' => '../apps/backend/Module.php'))); $response = $app->handle(); $response->send(); } catch (\Exception $e) { echo $e->getMessage(); }
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(); } } }
/** * Execute Phalcon Developer Tools * * @param string $path The path to the Phalcon Developer Tools * @param string $ip Optional IP address for securing Developer Tools * @return void * @throws \Exception if Phalcon extension is not installed * @throws \Exception if Phalcon version is not compatible Developer Tools * @throws \Phalcon\Exception if Application config could not be loaded */ public static function main($path, $ip = null) { if (!extension_loaded('phalcon')) { throw new \Exception(sprintf("Phalcon extension isn't installed, follow these instructions to install it: %s", Script::DOC_INSTALL_URL)); } if ($ip !== null) { self::$ip = $ip; } if (!defined('TEMPLATE_PATH')) { define('TEMPLATE_PATH', $path . '/templates'); } $basePath = dirname(getcwd()); // Dirs for search config file $configDirs = array($basePath . '/config/', $basePath . '/app/config/', $basePath . '/apps/frontend/config/', $basePath . '/apps/backend/config/'); $readed = false; foreach ($configDirs as $configPath) { if (file_exists($configPath . 'config.ini')) { $config = new ConfigIni($configPath . 'config.ini'); $readed = true; break; } else { if (file_exists($configPath . 'config.php')) { $config = (include $configPath . 'config.php'); if (is_array($config)) { $config = new Config($config); } $readed = true; break; } } } if ($readed === false) { throw new Exception(sprintf('Configuration file could not be loaded! Scanned dirs: %s', implode(', ', $configDirs))); } $loader = new Loader(); $loader->registerDirs(array($path . '/scripts/', $path . '/scripts/Phalcon/Web/Tools/controllers/')); $loader->registerNamespaces(array('Phalcon' => $path . '/scripts/')); $loader->register(); if (Version::getId() < Script::COMPATIBLE_VERSION) { throw new \Exception(sprintf("Your Phalcon version isn't compatible with Developer Tools, download the latest at: %s", Script::DOC_DOWNLOAD_URL)); } try { $di = new FactoryDefault(); $di->set('view', function () use($path) { $view = new View(); $view->setViewsDir($path . '/scripts/Phalcon/Web/Tools/views/'); return $view; }); $di->set('config', $config); $di->set('url', function () use($config) { $url = new Url(); $url->setBaseUri($config->application->baseUri); return $url; }); $di->set('flash', function () { return new Flash(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning')); }); $di->set('db', function () use($config) { if (isset($config->database->adapter)) { $adapter = $config->database->adapter; } else { $adapter = 'Mysql'; } if (is_object($config->database)) { $configArray = $config->database->toArray(); } else { $configArray = $config->database; } $className = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; unset($configArray['adapter']); return new $className($configArray); }); self::$di = $di; $app = new Application(); $app->setDi($di); echo $app->handle()->getContent(); } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "<br>"; echo nl2br($e->getTraceAsString()); } catch (\PDOException $e) { echo get_class($e), ': ', $e->getMessage(), "<br>"; echo nl2br($e->getTraceAsString()); } }
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(); } } }
$di['view'] = function () { $view = new View(); $view->setViewsDir('../app/views/'); $view->disableLevel(array(View::LEVEL_LAYOUT => true, View::LEVEL_MAIN_LAYOUT => true)); $view->registerEngines(array(".phtml" => 'voltService', ".volt" => 'voltService', ".json" => 'voltService')); return $view; }; // Setup a base URI so that all generated URIs include the "tutorial" folder $di['url'] = function () { $url = new Url(); $url->setBaseUri("/cgi/"); return $url; }; // Setup the tag helpers $di['tag'] = function () { return new Tag(); }; // add routing capabilities $di->set('router', function () { require '../app/config/routes.php'; return $router; }); // Handle the request $application = new Application($di); $handler = $application->handle(); $handler->setContentType("text/plain", "UTF-8"); echo $handler->getContent(); } catch (Exception $e) { echo "Exception: ", $e->getMessage(); //header('HTTP/1.0 404 Not Found'); }
public function modulesClosure(IntegrationTester $I) { $I->wantTo('handle request and get content by using single modules strategy (closure)'); Di::reset(); $_GET['_url'] = '/login'; $di = new FactoryDefault(); $di->set('router', function () { $router = new Router(false); $router->add('/index', ['controller' => 'index', 'module' => 'frontend', 'namespace' => 'Phalcon\\Test\\Modules\\Frontend\\Controllers']); $router->add('/login', ['controller' => 'login', 'module' => 'backend', 'namespace' => 'Phalcon\\Test\\Modules\\Backend\\Controllers']); return $router; }); $application = new Application(); $view = new View(); $application->registerModules(['frontend' => function ($di) use($view) { /** @var \Phalcon\DiInterface $di */ $di->set('view', function () use($view) { $view->setViewsDir(PATH_DATA . 'modules/frontend/views/'); return $view; }); }, 'backend' => function ($di) use($view) { /** @var \Phalcon\DiInterface $di */ $di->set('view', function () use($view) { $view->setViewsDir(PATH_DATA . 'modules/backend/views/'); return $view; }); }]); $application->setDI($di); $I->assertEquals('<html>here</html>' . PHP_EOL, $application->handle()->getContent()); }
<?php use Phalcon\Mvc\Application; define('APP_ROOT', __DIR__); try { require 'loader.php'; require 'di.php'; $app = new Application($di); echo $app->handle()->getContent(); } catch (Exception $e) { echo $e->getMessage(), PHP_EOL; echo $e->getTraceAsString(); }
* Attach plugins, components, modules to app */ include APP_PATH . 'Config/middleware.php'; include APP_PATH . 'Config/routes.php'; $modules = (include APP_PATH . 'Config/modules.php'); if (count($modules) > 0) { $app->registerModules($modules); } /** * Disable automatic rendering */ $app->useImplicitView(false); /** * Start application */ $app->handle(); /** * Set content */ $returnedValue = $app->dispatcher->getReturnedValue(); if ($returnedValue !== null && !is_string($returnedValue)) { $app->response->setJsonContent($returnedValue); } $response = $app->response; } catch (\Exception $e) { $response = $di->get(AppServices::RESPONSE); $response->setErrorContent($e, $config->debug); } /** * Send response */
/** * Runs the application performing all initializations * * @param $options * * @return mixed */ public function run($options) { $loaders = ['config', 'loader', 'session', 'permission', 'url', 'database', 'logger', 'environment', 'flash', 'flashsession', 'router', 'dispatcher', 'modelsmanager', 'metadata', 'annotations', 'view', 'cache', 'security', 'crypt', 'cookie', 'beanstalkd', 'acl', 'filemanager', 'authentication']; foreach ($loaders as $service) { $function = 'init' . ucfirst($service); $this->{$function}($options); } $application = new PhApplication(); $application->setDI($this->di); $modules = $this->getModules(); $application->registerModules($modules); $eventsManager = new PhEventsManager(); $application->setEventsManager($eventsManager); $eventsManager->attach('application:beforeHandleRequest', function ($event, $application) { $config = $this->di->get('config'); $response = $this->di->get('response'); $dispatcher = $this->di->get('dispatcher'); $cookie = $this->di->get('cookie'); //Detect mobile device $detect = new \Fly\Mobile_Detect(); if ($config->app_mobile == true && $detect->isMobile() && SUBDOMAIN != 'm' && $dispatcher->getModuleName() == 'common') { //begin redirect link to mobile version $curPageURL = \Fly\Helper::getCurrentUrl(); $curPageURL = str_replace(array('http://', 'https://'), array('http://m.', 'https://m.'), $curPageURL); $response->redirect($curPageURL, true); } //Setting language service $this->di->setShared('lang', function () use($dispatcher, $cookie) { $language = ''; // Detect language via cookie if ($cookie->has('language')) { $language = $cookie->get('language')->getValue(); } else { //Get default language $language = $this->config->defaultLanguage; } return new FlyTranslate(['module' => strtolower($dispatcher->getModuleName()), 'controller' => $dispatcher->getControllerName(), 'language' => $language]); }); }); return $application->handle()->getContent(); }
/** * Setup the phalcon application. * * @param null $uri * @return string */ protected function applicationSetup($uri = null) { $app = new Application($this->di); $app->useImplicitView('null' === $this->config['view']['default'] ? false : true); // set event manager for application $eventManager = $app->getDI()->getShared('eventsManager'); $this->setEventsManager($eventManager); $this->registerEvents(); /* * TODO This is bug on phalcon 2.0.4 */ $app->setEventsManager($this->getEventsManager()); return $app->handle($uri)->getContent(); }
public static function setExceptionHandler() { set_exception_handler(function (Exception $e) { \Logger::messages()->exception($e); if (!Config::instance()->production || PHP_SAPI == 'cli') { throw $e; } else { $app = new Application(DI::getDefault()); DI::getDefault()->set('last_exception', $e); switch (true) { case $e instanceof Http404Interface: case $e instanceof PhalconException: header('HTTP/1.1 404 Not Found'); header('Status: 404 Not Found'); exit($app->handle('/error/show404')->getContent()); default: header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 3600'); exit($app->handle('/error/show503')->getContent()); } } }); }