/** * 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(); }
public function setUp() { $di = new DI(); $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/path?foo=aaa&bar=bbb'; $_GET = array('_url' => '/path', 'foo' => 'aaa', 'bar' => 'bbb'); $request = new Request(); $request->setDI($di); $this->request = $request; $response = new Response(); $response->setDI($di); $this->response = $response; $eventsManager = new Manager(); $cors = new Cors(array(array('domain' => 'bar.com'))); $di->set('request', $request, true); $di->set('response', $response, true); $di->set('eventsManager', $eventsManager); $di->set('cors', $cors); $this->di = $di; $application = new Application(); $application->setDI($di); $application->setEventsManager($eventsManager); $this->application = $application; }
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()); }
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 setUp() { $di = new DI(); $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/path?foo=aaa&bar=bbb'; $_GET = array('_url' => '/path', 'foo' => 'aaa', 'bar' => 'bbb'); $request = new Request(); $request->setDI($di); $this->request = $request; $response = new Response(); $response->setDI($di); $dispatcher = new Dispatcher(); $dispatcher->setDI($di); $this->dispatcher = $dispatcher; $cache = new BackendCache(new FrontendCache()); $di->set('viewCache', $cache); $config = new Config(array('cache' => array('enable' => true))); $di->set('config', $config); $eventsManager = new Manager(); $di->set('request', $request, true); $di->set('response', $response, true); $di->set('dispatcher', $dispatcher, true); $di->set('eventsManager', $eventsManager); $this->di = $di; $application = new Application(); $application->setDI($di); $application->setEventsManager($eventsManager); $this->application = $application; }
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'); }
/** * @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'); }
/** * @param array $config * @return MvcApplication */ public static function createMvcFrom(array $config) : MvcApplication { $di = Di::createMvcFrom($config); $application = new MvcApplication($di); if ($di->has('applicationEventManager')) { $application->setEventsManager($di->getShared('applicationEventManager')); } $application->useImplicitView(isset($config['view'])); return $application; }
/** * Register application modules */ public function registerModules() { try { $modules = array(); foreach ($this->config as $moduleConfig) { $modules[$moduleConfig->moduleName] = array('className' => $moduleConfig->className, 'path' => $moduleConfig->path); } //add modules to application $this->application->registerModules($modules); } catch (Exception $e) { throw new \Foundation\Helper\Exception($e->getMessage(), $e->getCode()); } }
/** * @param Application $app */ public function boot(Application $app) { $options = $this->options; $app->getDI()->setShared('aws', function () use($options) { $aws = Aws::factory($options); $aws->getEventDispatcher()->addListener('service_builder.create_client', function (Event $event) { $clientConfig = $event['client']->getConfig(); $commandParams = $clientConfig->get(Client::COMMAND_PARAMS) ?: array(); $clientConfig->set(Client::COMMAND_PARAMS, array_merge_recursive($commandParams, array(UserAgentListener::OPTION => 'Phalcon/' . Application::VERSION))); }); return $aws; }); }
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(); }
/** * 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(); }
/** * Initialize phalcon application * @return PhalconApplication */ protected function initPhalconApplication() { $diFactory = $this->diManager->getDI(); $moduleHandler = $diFactory->get('moduleHandler'); // Register autoloader (new Autoloader($diFactory))->register(); // Register services and routers $this->diManager->initInvokableServices()->initFactoriedServices()->initRouterDi(); // Init listeners (new Listener($diFactory))->listenApplicationEvents(new Listener\Application())->listenDispatchEvents(new Listener\Dispatch()); // Register modules $application = new PhalconApplication($diFactory); $application->setEventsManager($diFactory['eventsManager']); $application->registerModules($moduleHandler->getRegisteredModules()); return $application; }
public function __construct($env, \Phalcon\DiInterface $di = null) { /** * set environment */ self::$env = strtolower($env); switch ($this::$env) { case self::ENV_PRODUCTION: ini_set('display_errors', 0); ini_set('display_startup_errors', 0); error_reporting(0); break; case self::ENV_TESTING: case self::ENV_DEVELOPMENT: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(-1); break; default: throw new \Exception('Wrong application $env passed: ' . $env); } /** * register di */ if (is_null($di)) { $di = new \Phalcon\DI\FactoryDefault(); } /** * Read the configuration */ $config =& $this->config; $config = new \Phalcon\Config(include ROOT_PATH . '/config/config.php'); $di->set('config', $config); parent::__construct($di); }
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; }
/** * Instance construct */ public function __construct() { /** * Create default DI */ $this->di = new DI\FactoryDefault(); $this->config = ZFactory::config(); if ($this->config->website->baseUri == '') { if ($_SERVER['SERVER_PORT'] != '443') { $this->config->website->baseUri = 'http://' . $_SERVER['HTTP_HOST'] . str_replace(['/public/index.php', '/index.php'], '', $_SERVER['SCRIPT_NAME']); } else { $this->config->website->baseUri = 'https://' . $_SERVER['HTTP_HOST'] . str_replace(['/public/index.php', '/index.php'], '', $_SERVER['SCRIPT_NAME']); } } $this->di->set('config', $this->config); /** * @define bool DEBUG */ define('DEBUG', $this->config->debug); /** * @define string BASE_URI */ define('BASE_URI', $this->config->website->baseUri); include ROOT_PATH . '/app/libraries/Core/Utilities/ZFunctions.php'; parent::__construct($this->di); }
/** * @param string $env * @param array $configuration * @param \Phalcon\DiInterface $di * @throws \Exception */ public function __construct($env, array $configuration, \Phalcon\DiInterface $di = null) { $this->env = strtolower($env); $this->configuration = $configuration; switch ($this->env) { case self::ENV_PRODUCTION: case self::ENV_STAGING: ini_set('display_errors', 0); ini_set('display_startup_errors', 0); error_reporting(0); break; case self::ENV_TESTING: case self::ENV_DEVELOPMENT: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(-1); break; default: throw new \Exception('Wrong application $env passed: ' . $env); } if (is_null($di)) { $di = new \Phalcon\DI\FactoryDefault(); } parent::__construct($di); }
/** * 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('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(); } }
/** * Application constructor. * @param \Phalcon\DiInterface|null $dependencyInjector * @param Config $config */ public function __construct(\Phalcon\DiInterface $dependencyInjector = null, Config $config) { parent::__construct($dependencyInjector); $this->config = $config; $this->_eventsManager = new Manager(); $dependencyInjector->set('config', $config); $this->attachBootstrapEvents(); }
/** * 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 = ['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(); }
/** * @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(); } }
/** * Bootstrap constructor - set the dependency Injector * * @package las * @version 1.0 * * @param \Phalcon\DiInterface $di */ public function __construct(\Phalcon\DiInterface $di) { $this->_di = $di; $loaders = array('config', 'loader', 'timezone', 'i18n', 'db', 'filter', 'flash', 'crypt', 'auth', 'session', 'cookie', 'cache', 'url', 'router'); // Register services foreach ($loaders as $service) { $this->{$service}(); } // Register modules $this->registerModules(array('frontend' => array('className' => 'Las\\Frontend\\Module', 'path' => ROOT_PATH . '/app/frontend/Module.php'), 'admin' => array('className' => 'Las\\Backend\\Module', 'path' => ROOT_PATH . '/app/backend/Module.php'), 'doc' => array('className' => 'Las\\Doc\\Module', 'path' => ROOT_PATH . '/app/doc/Module.php'))); // Register the app itself as a service $this->_di->set('app', $this); // Set the dependency Injector parent::__construct($this->_di); }
/** * HMVCApplication Constructor * * @param Phalcon\DiInterface */ public function __construct(DiInterface $di) { $loader = new Loader(); //Application Loader $loader->registerDirs(array('../app/controllers/'))->register(); //Register the view service $di['view'] = function () { $view = new View(); $view->setViewsDir('../app/views/'); return $view; }; //Register the app itself as a service $di['app'] = $this; //Sets the parent Id parent::setDI($di); }
/** * Constructor */ public function __construct() { if (empty($this->_configPath)) { $class = new \ReflectionClass($this); throw new \Engine\Exception('Application has no config path: ' . $class->getFileName()); } $loader = new \Phalcon\Loader(); $loader->registerNamespaces(['Engine' => ROOT_PATH . '/engine']); $loader->register(); // create default di $di = new \Phalcon\DI\FactoryDefault(); // get config $this->_config = (include_once ROOT_PATH . $this->_configPath); // Store config in the Di container $di->setShared('config', $this->_config); parent::__construct($di); }
protected function initApplication() { $di = $this->getDI(); if (!$this->getUserOption('app') instanceof Application) { $this->setUserOption('app', new Application()); } $this->app = $this->getUserOption('app'); $this->app->setDI($di); $this->app->setEventsManager($di->get('eventsManager')); // disable implicit views if using simple views if ($di->has('view') && !$di->get('view') instanceof ViewInterface) { $this->app->useImplicitView(false); } $di->setShared('app', $this->app); if (!defined('APP_ENV')) { define('APP_ENV', getenv('APP_ENV') ?: static::ENV_PRODUCTION); } }
/** * 构建网站服务入口(Constructor) * * @param $di */ public function __construct(\Phalcon\DiInterface $di) { $this->_di = $di; $loaders = array('loader', 'config', 'timezone', 'db', 'crypt', 'cache', 'language', 'url', 'router'); // 注册各载入服务(Register services) try { foreach ($loaders as $service) { $this->{$service}(); } } catch (\Exception $e) { exit('网站模块注册出错!请通知管理员尽快恢复正常运行,谢谢!'); } // 注册服务模块(Register modules) $this->registerModules(array('home' => array('className' => 'App\\Home\\Module', 'path' => APP_PATH . '/home/Module.php'), 'admin' => array('className' => 'App\\Admin\\Module', 'path' => APP_PATH . '/admin/Module.php'), 'backend' => array('className' => 'App\\Backend\\Module', 'path' => APP_PATH . '/backend/Module.php'))); // 注册本类为应用服务(Register the app itself as a service) $this->_di->set('app', $this); // 调用父类注册入口(Sets the parent Di) parent::setDI($this->_di); }
public function __construct(\Phalcon\DI $di = null) { if (!self::$_alreadyInit) { self::$_alreadyInit = true; self::$_instance = $this; self::$_token = Tokenizer::randomToken(); $this->loader = new Autoloader(self::$_token); new Constants(); $this->definePermissionGroups(); $this->di = $di == null ? new DependencyInjection() : $di; $this->_registerServices(); parent::__construct($this->di); $this->_registerDefaultModule(); $this->_registerModules(); $this->_registerListeners(); $this->debug = new \Phalcon\Debug(); } else { self::throwException(null, 100); } }
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()); } } }); }