protected function classSetUp() { $di = new \Phalcon\DI\FactoryDefault(); $di->set('collectionManager', function () { return new \Phalcon\Mvc\Collection\Manager(); }, true); $di->set('mongo', function () { $mongo = new \MongoClient('localhost:27017', ['connect' => true, 'socketTimeoutMS' => 60000]); return $mongo->selectDB('reach_testing'); }, true); /** @var \MongoDB $db */ $db = $di->get('mongo'); $collection = $db->selectCollection('test_model_mongo_document'); $collection->drop(); /** * @todo http://php.net/manual/en/mongocollection.ensureindex.php */ $collection->ensureIndex(['object.type' => 1]); $collection->ensureIndex(['object.rnd' => 1]); $collection->ensureIndex(['created' => 1]); $this->_memory = memory_get_usage(true); }
public function testCrash() { $di = new Phalcon\DI\FactoryDefault(); $bag = $di->get('sessionBag', array('dummy')); $this->assertTrue(true); }
/** * This methods registers the services to be used by the application */ protected function _registerServices() { $di = new \Phalcon\DI\FactoryDefault(); // Registering a Config shared-service $di->setShared('config', function () { $config['main'] = (include ROOT_DIR . "/config/main.php"); $config['db'] = (include ROOT_DIR . "/config/db.php"); $config['router'] = (include ROOT_DIR . "/config/router.php"); return new \Phalcon\Config($config); }); $config = $di->get('config'); // Change FactoryDefault default Router service $di->getService('router')->setDefinition(function () use($config) { $router = new \Phalcon\Mvc\Router(); //Setup routes from /config/router.php foreach ($config->router->toArray() as $key => $value) { $router->add($key, $value); } // Mount each module routers $router->mount(new \App\Frontend\Router()); $router->mount(new \App\Backend\Router()); // URI_SOURCE_SERVER_REQUEST_URI $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); // Remove trailing slashes automatically $router->removeExtraSlashes(true); // Setting a specific default using an array // DefaultModule // DefaultNamespace // DefaultController // DefaultAction $router->setDefaults(array('modul' => 'frontend', 'namespace' => 'App\\Frontend\\Controllers\\', 'controller' => 'index', 'action' => 'index')); // Set 404 paths $router->notFound(["controller" => "error", "action" => "error404"]); return $router; }); // Registering a View shared-service $di->setShared('view', function () { return new \Phalcon\Mvc\View(); }); // Registering a Mysql shared-service $di->setShared('mysql', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->mysql->toArray()); }); // Registering a Db shared-service $di->setShared('db', function () use($di) { return $di->get('mysql'); }); // Registering a Url shared-service $di->setShared('url', function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }); // Start the Session service $di->get('session')->start(); // Setup the Crypt service $di->get('crypt')->setMode(MCRYPT_MODE_CFB)->setKey($config->main->crypt_key); // Setup the Security service $di->get('security')->setWorkFactor(12); // Registering a custom authentication shared-service $di->setShared('auth', function () { return new \App\Common\Libs\Auth(); }); $this->setDI($di); }
/** * Set Dependency Injector with configuration variables * * @throws Exception on bad database adapter * @param string $file full path to configuration file */ public function setConfig($file) { if (!file_exists($file)) { throw new \Exception('Unable to load configuration file'); } $environment = getenv('APPLICATION_ENV') ?: 'production'; // load in application config $config = new \Phalcon\Config(require $file); $envConfig = $this->getConfigPath() . '/' . $environment . '.' . $this->getConfigFileName(); // load in alternative configs for the environment if (file_exists($envConfig)) { $config2 = new \Phalcon\Config(include $envConfig); $config->merge($config2); } $di = $this->getDI(); if (null === $di) { $di = new \Phalcon\DI\FactoryDefault(); } $di->set('config', $config); $di->set('db', function () use($di) { $type = strtolower($di->get('config')->database->adapter); $creds = array('host' => $di->get('config')->database->host, 'username' => $di->get('config')->database->username, 'password' => $di->get('config')->database->password, 'dbname' => $di->get('config')->database->dbname); if ($type == 'mysql') { $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($creds); } elseif ($type == 'postgres') { $connection = new \Phalcon\Db\Adapter\Pdo\Postgesql($creds); } elseif ($type == 'sqlite') { $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($creds); } else { throw new \Exception('Bad Database Adapter'); } return $connection; }); $this->setDI($di); unset($environment, $config); }
$di->setShared('router', function () { return require APP_ROOT . '/config/routes.php'; }); $di->setShared('url', function () use($di) { $url = new \ApiDocs\Components\Url(); $url->setBaseUri('/api/'); return $url; }); $di->setShared('tag', function () { return new \ApiDocs\Components\Tag(); }); $di->setShared('view', function () use($di) { $view = new Phalcon\Mvc\View(); $view->setViewsDir(APP_ROOT . '/views/'); $view->registerEngines(array('.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.volt' => function ($view, $di) { $config = $di->get('config'); $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions((array) $config->voltOptions); $volt->getCompiler()->addFunction('tr', function ($key) { return "translate({$key})"; }); return $volt; })); return $view; }); $di->setShared('db', function () use($di) { $connection = new DbAdapter((array) $di->get('config')->db); return $connection; }); $di->setShared('dispatcher', function () use($di) { $eventsManager = $di->get('eventsManager');
$di->set('router', function () use($config) { $router = new \Phalcon\Mvc\Router(); //加载默认模块 $key = $config->modules->default; if ($key && $config->modules->{$key}->used == 1) { $router->setDefaultModule('frontend'); } return $router; }, true); //加载视图 $view = new Phalcon\MVC\View(); $view->registerEngines(array('.html' => 'Phalcon\\Mvc\\View\\Engine\\Php')); $di->set('view', $view); //session 延迟加载 $di->set('session', new Phalcon\Session\Adapter\Files()); $di->get('session')->start(); //加载DB负载均衡 BalanceDb::config($config->balanceDb->toArray()); foreach ($config->balanceDb->toArray() as $dbKey => $currentConfig) { if ($dbKey == 'default') { continue; } $keyWrite = 'db' . ucfirst($dbKey); $keyRead = $keyWrite . '_read'; $dbWriteConfig = $currentConfig['write']['db']; $di->set($keyWrite, function () use($dbWriteConfig) { return new Phalcon\Db\Adapter\Pdo\Mysql($dbWriteConfig); }); $dbReadConfig = current($currentConfig['reads']); $di->set($keyRead, function () use($dbReadConfig) { return new Phalcon\Db\Adapter\Pdo\Mysql($dbReadConfig);
require_once 'vendor/autoload.php'; error_reporting(0); /** * Set up the dependency injector */ $di = new Phalcon\DI\FactoryDefault(); // Redis client $di->set('redis', function () { $ip = defined('REDIS_IP') ? REDIS_IP : '127.0.0.1'; $port = defined('REDIS_PORT') ? REDIS_PORT : '6379'; return new Predis\Client('tcp://' . $ip . ':' . $port); }); // poststore service $di->set('poststore', function () use($di) { // constructor injection return new Service\PostStore($di->get('redis')); }); // rawpost model $di->set('rawpost', function () { return new Model\RawPost(); }); /** * Build app, set routes */ $app = new Phalcon\Mvc\Micro($di); // Matches any route starting with i $app->post('/(i[a-z\\.]+)', function () use($app) { $response = new Phalcon\Http\Response(); // collect json data $rawpost = $app->di->get('rawpost'); $rawpost->setRawpost($app->request->getJsonRawBody(true));
<?php // demo inits , maybe from filesystem or databases or registry $inits = array('RcS', 'Nfs', 'Apache'); // creates the autoloader $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . DIRECTORY_SEPARATOR))->register(); $di = new \Phalcon\DI\FactoryDefault(); // effective java 's factory pattern $di->set('Apache', function () { return new Nginx(); }); $eventsManager = $di->get('eventsManager'); foreach ($inits as $init) { try { $handle = $di->get($init); $eventsManager->attach('upstart', $handle); } catch (Exception $e) { // class not found } } // startup $eventsManager->fire('upstart:filesystem', $eventsManager); $eventsManager->fire('upstart:networking', $eventsManager); $eventsManager->fire('upstart:networkFilesystem', $eventsManager); $eventsManager->fire('upstart:startup', $eventsManager);
case DIST_ENV: ini_set("display_errors", 0); ini_set("log_errors", 1); error_reporting(E_ALL); break; default: error_log('Error: The application ENV constant is not set correctly.'); exit(1); } // Create the dependency injector for the Phalcon framework $di = new Phalcon\DI\FactoryDefault(); $di->setShared('config', function () { $config = (require __DIR__ . "/config/config.php"); return $config; }); $config = $di->get('config'); if (!file_exists($config->path->tmpDir)) { mkdir($config->path->tmpDir); } // Setup composer autoloading so that it doesn't need to be specified in each Module require_once $config->path->composerDir . 'autoload.php'; require $config->path->configDir . 'services.php'; require $config->path->configDir . 'services_web.php'; if (DEV) { class_alias('\\Webird\\Debug', '\\Dbg', true); } // Handle the request and inject DI $application = new \Phalcon\Mvc\Application($di); $application->registerModules(['web' => ['className' => 'Webird\\Web\\Module'], 'admin' => ['className' => 'Webird\\Admin\\Module'], 'api' => ['className' => 'Webird\\Api\\Module']]); try { echo $application->handle()->getContent();
ini_set('date.timezone', 'Asia/Shanghai'); try { $loader = new \Phalcon\Loader(); $loader->registerNamespaces(array("Phalcon_wifi\\Common\\Models" => "../apps/Common/models", "Phalcon_wifi\\Common\\Controllers" => "../apps/Common/controllers", "Phalcon_wifi\\Common\\Config" => "../apps/Common/config", "Phalcon_wifi\\Common\\Ext" => "../apps/Common/ext", "Phalcon_wifi\\Common\\Validate" => "../apps/Common/validate")); $loader->register(); $di = new \Phalcon\DI\FactoryDefault(); $di["router"] = function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule("Admin"); $router->setDefaultNamespace("Phalcon_wifi\\Admin\\Controllers"); $router->add('/:controller/:action/:params', array('module' => 'Admin', 'controller' => 1, 'action' => 2, 'params' => 3))->setName("common"); return $router; }; $di["url"] = function () use($di) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($di->get("config")->get("common")["baseuri"]); return $url; }; $di["session"] = function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }; $di["db"] = function () use($di) { $config = $di->get("config")->get("common")["db"]; $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config["host"], "username" => $config["username"], "password" => $config["password"], "dbname" => $config["dbname"], "charset" => $config["charset"])); $eventsManager = new \Phalcon\Events\Manager(); $dblog = $di->get("config")->get("common")["dblog"]; $logger = new \Phalcon\Logger\Adapter\File(__DIR__ . $dblog); $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) { $sqlVariables = $connection->getSQLVariables();
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new \Phalcon\DI\FactoryDefault(); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }); /** * Setup the translator */ $di->set('translate', function () use($di) { $dispatcher = $di->get('dispatcher'); $language = $dispatcher->getParam("lang"); $langDir = __DIR__ . '/../app/lang/'; if (file_exists("{$langDir}{$language}.php")) { require_once "{$langDir}{$language}.php"; } else { require_once "{$langDir}en.php"; } return new \Phalcon\translate\Adapter\NativeArray(array("content" => $messages)); }); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir);
public function testFactoryDefault() { $factoryDefault = new Phalcon\DI\FactoryDefault(); $request = $factoryDefault->get('request'); $this->assertEquals(get_class($request), 'Phalcon\\Http\\Request'); $response = $factoryDefault->get('response'); $this->assertEquals(get_class($response), 'Phalcon\\Http\\Response'); $filter = $factoryDefault->get('filter'); $this->assertEquals(get_class($filter), 'Phalcon\\Filter'); $escaper = $factoryDefault->get('escaper'); $this->assertEquals(get_class($escaper), 'Phalcon\\Escaper'); $url = $factoryDefault->get('url'); $this->assertEquals(get_class($url), 'Phalcon\\Mvc\\Url'); $flash = $factoryDefault->get('flash'); $this->assertEquals(get_class($flash), 'Phalcon\\Flash\\Direct'); $dispatcher = $factoryDefault->get('dispatcher'); $this->assertEquals(get_class($dispatcher), 'Phalcon\\Mvc\\Dispatcher'); $modelsManager = $factoryDefault->get('modelsManager'); $this->assertEquals(get_class($modelsManager), 'Phalcon\\Mvc\\Model\\Manager'); $modelsMetadata = $factoryDefault->get('modelsMetadata'); $this->assertEquals(get_class($modelsMetadata), 'Phalcon\\Mvc\\Model\\MetaData\\Memory'); $router = $factoryDefault->get('router'); $this->assertEquals(get_class($router), 'Phalcon\\Mvc\\Router'); $session = $factoryDefault->get('session'); $this->assertEquals(get_class($session), 'Phalcon\\Session\\Adapter\\Files'); $security = $factoryDefault->get('security'); $this->assertEquals(get_class($security), 'Phalcon\\Security'); }
public function run() { $di = new \Phalcon\DI\FactoryDefault(); $config = (include APPLICATION_PATH . '/config/application.php'); $di->set('config', $config); $registry = new \Phalcon\Registry(); $loader = new \Phalcon\Loader(); $loader->registerNamespaces($config->loader->namespaces->toArray()); $loader->register(); $loader->registerDirs(array(APPLICATION_PATH . "/plugins/")); $db = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset)); $di->set('db', $db); $view = new \Phalcon\Mvc\View(); define('MAIN_VIEW_PATH', '../../../views/'); $view->setMainView(MAIN_VIEW_PATH . 'main'); $view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/'); $view->setPartialsDir(MAIN_VIEW_PATH . '/partials/'); $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => APPLICATION_PATH . '/cache/volt/')); $phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di); $viewEngines = array(".volt" => $volt, ".phtml" => $phtml); $registry->viewEngines = $viewEngines; $view->registerEngines($viewEngines); if (isset($_GET['_ajax']) && $_GET['_ajax']) { $view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT); } $di->set('view', $view); $viewSimple = new \Phalcon\Mvc\View\Simple(); $viewSimple->registerEngines($viewEngines); $di->set('viewSimple', $viewSimple); $url = new \Phalcon\Mvc\Url(); $url->setBasePath('/'); $url->setBaseUri('/'); $cacheFrontend = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 60, "prefix" => HOST_HASH)); switch ($config->cache) { case 'file': $cache = new \Phalcon\Cache\Backend\File($cacheFrontend, array("cacheDir" => __DIR__ . "/cache/backend/")); break; case 'memcache': $cache = new \Phalcon\Cache\Backend\Memcache($cacheFrontend, array("host" => "localhost", "port" => "11211")); break; } $di->set('cache', $cache); $di->set('modelsCache', $cache); switch ($config->metadata_cache) { case 'memory': $modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory(); break; case 'apc': $modelsMetadata = new \Phalcon\Mvc\Model\MetaData\Apc(array("lifetime" => 60, "prefix" => HOST_HASH)); break; } $di->set('modelsMetadata', $modelsMetadata); /** * CMS Конфигурация */ $cmsModel = new \Cms\Model\Configuration(); $cms = $cmsModel->getConfig(); // @todo Будет отдельный раздел конфигурации для управления языками. Пока заглушка. $cms['languages'] = [['name' => 'Русский', 'iso' => 'ru', 'locale' => 'ru_RU'], ['name' => 'English', 'iso' => 'en', 'locale' => 'en_EN']]; $registry->cms = $cms; // Отправляем в Registry $application = new \Phalcon\Mvc\Application(); $application->registerModules($config->modules->toArray()); $router = new \Application\Mvc\Router\DefaultRouter(); foreach ($application->getModules() as $module) { $className = str_replace('Module', 'Routes', $module['className']); if (class_exists($className)) { $class = new $className(); $router = $class->init($router); } } $di->set('router', $router); $eventsManager = new \Phalcon\Events\Manager(); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher, $di) use($di) { new LocalizationPlugin($dispatcher); new AclPlugin($di->get('acl'), $dispatcher); }); $profiler = new \Phalcon\Db\Profiler(); $eventsManager->attach('db', function ($event, $db) use($profiler) { if ($event->getType() == 'beforeQuery') { $profiler->startProfile($db->getSQLStatement()); } if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); } }); $db->setEventsManager($eventsManager); $di->set('profiler', $profiler); $dispatcher->setEventsManager($eventsManager); $di->set('dispatcher', $dispatcher); $session = new \Phalcon\Session\Adapter\Files(); $session->start(); $di->set('session', $session); $acl = new \Application\Acl\DefaultAcl(); $di->set('acl', $acl); $assets = new \Phalcon\Assets\Manager(); $di->set('assets', $assets); $flash = new \Phalcon\Flash\Session(array('error' => 'ui red inverted segment', 'success' => 'ui green inverted segment', 'notice' => 'ui blue inverted segment', 'warning' => 'ui orange inverted segment')); $di->set('flash', $flash); $di->set('helper', new \Application\Mvc\Helper()); $di->set('registry', $registry); $assetsManager = new \Phalcon\Assets\Manager(); $di->set('assets', $assetsManager); $application->setDI($di); $this->dispatch($di); }
return $flash; }; $di['flashSession'] = function () { $flash = new \Phalcon\Flash\Session(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning')); return $flash; }; $di['session'] = function () { $session = new Session(); $session->start(); return $session; }; $di['forms'] = function () { $formsManager = new FormsManager(); $forms = (array) @(include __DIR__ . '/forms.php'); foreach ($forms as $name => $form) { $formsManager->set($name, $form); } return $formsManager; }; $di['dispatcher'] = function () use($di) { /** @var \Phalcon\Events\Manager $eventsManager */ $eventsManager = $di->getShared('eventsManager'); $eventsManager->attach('dispatch', $di->get('exceptionPlugin')); $eventsManager->attach('dispatch', $di->get('authPlugin')); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }; $di['exceptionPlugin'] = '\\Plugin\\Exception'; $di['authPlugin'] = ['className' => '\\Plugin\\Auth', 'arguments' => [['type' => 'service', 'name' => 'acl']]]; return $di;
/** * Prior to 2.0.0 exception message was "Service 'servicewhichdoesnotexist' wasn't found in the dependency injection container" * * @expectedException \Phalcon\Di\Exception * @expectedExceptionMessage Service 'servicewhichdoesnotexist' wasn't found in the dependency injection container */ public function testGettingNonExistentServiceShouldThrowExceptionWithExpectedMessage() { $di = new \Phalcon\DI\FactoryDefault(); $di->get('servicewhichdoesnotexist'); }
$di->set('mongo', function () use($config) { $mongo = new \MongoClient(); return $mongo->selectDb($config->mongo->db); }, true); /** * Start the session the first time some component request the session service */ $di->set('session', function () use($config) { $sessionAdapter = new SessionAdapter($config->session->toArray()); if (!$sessionAdapter->isStarted()) { $sessionAdapter->start(); } return $sessionAdapter; }, true); $di->set('sessionManager', function () use($di) { $session = new Vegas\Session($di->get('session')); return $session; }, true); /** * Password manager for standard user */ $di->set('userPasswordManager', '\\Vegas\\Security\\Password\\Adapter\\Standard', true); /** authentications **/ //standard user $di->set('auth', function () use($di) { $adapter = new \Vegas\Security\Authentication\Adapter\Standard($di->get('userPasswordManager')); $adapter->setSessionStorage($di->get('sessionManager')->createScope('auth')); $auth = new \Vegas\Security\Authentication($adapter); return $auth; }, true); //no credential
/** * Set Dependency Injector with configuration variables * * @throws Exception on bad database adapter * @param string $file full path to configuration file */ public function setConfig($file) { if (!file_exists($file)) { throw new \Exception('Unable to load configuration file'); } $di = new \Phalcon\DI\FactoryDefault(); $di->set('config', new \Phalcon\Config(require $file)); $di->set('db', function () use($di) { $type = strtolower($di->get('config')->database->adapter); $creds = array('host' => $di->get('config')->database->host, 'username' => $di->get('config')->database->username, 'password' => $di->get('config')->database->password, 'dbname' => $di->get('config')->database->name); if ($type == 'mysql') { $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($creds); } else { if ($type == 'postgres') { $connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($creds); } else { if ($type == 'sqlite') { $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($creds); } else { throw new Exception('Bad Database Adapter'); } } } return $connection; }); $this->setDI($di); }