public function testApplicationModulesDefinitionClosure() { // Creates the autoloader $loader = new \Phalcon\Loader(); $loader->registerNamespaces(array('Frontend\\Controllers' => __DIR__ . '/modules/frontend/controllers/', 'Backend\\Controllers' => __DIR__ . '/modules/backend/controllers/')); $loader->register(); $_GET['_url'] = '/login'; Phalcon\DI::reset(); $di = new Phalcon\DI\FactoryDefault(); $di->set('router', function () { $router = new Phalcon\Mvc\Router(false); $router->add('/index', array('controller' => 'index', 'module' => 'frontend', 'namespace' => 'Frontend\\Controllers\\')); $router->add('/login', array('controller' => 'login', 'module' => 'backend', 'namespace' => 'Backend\\Controllers\\')); return $router; }); $application = new Phalcon\Mvc\Application(); $view = new \Phalcon\Mvc\View(); $application->registerModules(array('frontend' => function ($di) use($view) { $di->set('view', function () use($view) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . '/modules/frontend/views/'); return $view; }); }, 'backend' => function ($di) use($view) { $di->set('view', function () use($view) { $view->setViewsDir(__DIR__ . '/modules/backend/views/'); return $view; }); })); $application->setDi($di); $this->assertEquals($application->handle()->getContent(), '<html>here</html>' . PHP_EOL); $loader->unregister(); }
protected function _getDI($dbService) { Phalcon\DI::reset(); $di = new Phalcon\DI\FactoryDefault(); $di->set('db', $dbService, true); return $di; }
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 static function createDi($dbOpts) { $di = new \Phalcon\DI\FactoryDefault(); $di->set('db', function () use($dbOpts) { return new \Phalcon\Db\Adapter\Pdo\Mysql($dbOpts); }); return $di; }
public function run() { $di = new \Phalcon\DI\FactoryDefault(); // Config require_once APPLICATION_PATH . '/modules/Cms/Config.php'; $config = \Cms\Config::get(); $di->set('config', $config); // Registry $registry = new \Phalcon\Registry(); $di->set('registry', $registry); // Loader $loader = new \Phalcon\Loader(); $loader->registerNamespaces($config->loader->namespaces->toArray()); $loader->registerDirs([APPLICATION_PATH . "/plugins/"]); $loader->register(); require_once APPLICATION_PATH . '/../vendor/autoload.php'; // Database $db = new \Phalcon\Db\Adapter\Pdo\Mysql(["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 $this->initView($di); // URL $url = new \Phalcon\Mvc\Url(); $url->setBasePath($config->base_path); $url->setBaseUri($config->base_path); $di->set('url', $url); // Cache $this->initCache($di); // CMS $cmsModel = new \Cms\Model\Configuration(); $registry->cms = $cmsModel->getConfig(); // Отправляем в Registry // Application $application = new \Phalcon\Mvc\Application(); $application->registerModules($config->modules->toArray()); // Events Manager, Dispatcher $this->initEventManager($di); // Session $session = new \Phalcon\Session\Adapter\Files(); $session->start(); $di->set('session', $session); $acl = new \Application\Acl\DefaultAcl(); $di->set('acl', $acl); // JS Assets $this->initAssetsManager($di); // Flash helper $flash = new \Phalcon\Flash\Session(['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()); // Routing $this->initRouting($application, $di); $application->setDI($di); // Main dispatching process $this->dispatch($di); }
/** * Method to create the Phalcon MVC Micro Object * @return object Phalcon MVC Micro Object */ private function createPhalcon() { $di = new \Phalcon\DI\FactoryDefault(); if (AppConfig::get('pp', 'usePhalconDatabaseObject') == 'on') { //Set up the database service $di->set('db', function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(AppConfig::getSection('database')); }); } return new \Phalcon\Mvc\Micro($di); }
/** * Register the services here to make them general or register in * the ModuleDefinition to make them module-specific. */ protected function _registerServices() { $loader = new \Phalcon\Loader(); /** * We're a registering a set of directories taken from the configuration file */ /* $loader->registerDirs( array( __DIR__ . '/../library/', __DIR__ . '/../vendor/', ) )->register(); */ // Init a DI $di = new \Phalcon\DI\FactoryDefault(); // Registering a router: $defaultModule = self::DEFAULT_MODULE; $modules = self::$modules; $di->set('router', function () use($defaultModule, $modules) { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule($defaultModule); foreach ($modules as $moduleName => $module) { // do not route default module if ($defaultModule == $moduleName) { continue; } $router->add('#^/' . $moduleName . '(|/)$#', array('module' => $moduleName, 'controller' => 'index', 'action' => 'index')); $router->add('#^/' . $moduleName . '/([a-zA-Z0-9\\_]+)[/]{0,1}$#', array('module' => $moduleName, 'controller' => 1)); $router->add('#^/' . $moduleName . '[/]{0,1}([a-zA-Z0-9\\_]+)/([a-zA-Z0-9\\_]+)(/.*)*$#', array('module' => $moduleName, 'controller' => 1, 'action' => 2, 'params' => 3)); } return $router; }); /** * The URL component is used to generate all kind of urls in the application */ $di['url'] = function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }; /** * Start the session the first time some component request the session service */ $di['session'] = function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }; $this->setDI($di); }
public function testIssue1486() { $di = new Phalcon\DI\FactoryDefault(); $di->getshared('url')->setBaseUri('/'); \Phalcon\Tag::setDI($di); $html = \Phalcon\Tag::stylesheetLink('css/phalcon.css'); $this->assertEquals($html, '<link rel="stylesheet" href="/css/phalcon.css" type="text/css" />' . PHP_EOL); $html = \Phalcon\Tag::stylesheetLink(array('css/phalcon.css')); $this->assertEquals($html, '<link rel="stylesheet" href="/css/phalcon.css" type="text/css" />' . PHP_EOL); $html = \Phalcon\Tag::javascriptInclude('js/phalcon.js'); $this->assertEquals($html, '<script src="/js/phalcon.js" type="text/javascript"></script>' . PHP_EOL); $html = \Phalcon\Tag::javascriptInclude(array('js/phalcon.js')); $this->assertEquals($html, '<script src="/js/phalcon.js" type="text/javascript"></script>' . PHP_EOL); }
/** * Register the services here to make them general or register in the ModuleDefinition to make them module-specific */ protected function _registerServices() { $config = (include __DIR__ . "/../apps/config/config.php"); $di = new \Phalcon\DI\FactoryDefault(); $loader = new \Phalcon\Loader(); /** * We're a registering a set of directories taken from the configuration file */ $loader->registerDirs(array($config->application->libraryDir, $config->application->pluginDir))->register(); //Registering a router $di->set('router', function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule("frontend"); $router->add('/:controller/:action', array('module' => 'frontend', 'controller' => 1, 'action' => 2)); $router->add("/cats/index", array('module' => 'frontend', 'controller' => 'categories', 'action' => 'index')); $router->add("/cat/:params", array('module' => 'frontend', 'controller' => 'categories', 'action' => 'cat', 'params' => 1)); $router->add("/ask/:params", array('module' => 'frontend', 'controller' => 'ask', 'action' => 'ask', 'params' => 1)); $router->add("/admin/:controller/:action/:params", array('module' => 'backend', 'controller' => 1, 'action' => 2, 'params' => 3)); return $router; }); $di->set('db', function () use($config) { $mysql = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); $mysql->query("set names 'utf8'"); return $mysql; }); $di->set('volt', function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => $config->volt->path, 'compiledExtension' => $config->volt->extension, 'compiledSeparator' => $config->volt->separator, 'stat' => (bool) $config->volt->stat)); return $volt; }); //Set the views cache service $di->set('viewCache', function () { //Cache data for one day by default $frontCache = new Phalcon\Cache\Frontend\Output(array("lifetime" => 86400)); //Memcached connection settings $cache = new Phalcon\Cache\Backend\File($frontCache, array("cacheDir" => "../apps/caches/")); return $cache; }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function () use($config) { if (isset($config->models->metadata)) { $metaDataConfig = $config->models->metadata; $metadataAdapter = 'Phalcon\\Mvc\\Model\\Metadata\\' . $metaDataConfig->adapter; return new $metadataAdapter(); } else { return new Phalcon\Mvc\Model\Metadata\Memory(); } }); //Start the session the first time some component request the session service $di->set('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $this->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); }
public function setup() { static::$config = (require __DIR__ . '/../config.php'); // append biller conf static::$config['biller'] = ['key' => self::API_KEY, 'custom_id' => 'id', 'custom_email' => 'email']; $di = new \Phalcon\DI\FactoryDefault(); $di->set('config', static::$config); $di->set('db', function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => '127.0.0.1', 'username' => 'root', 'password' => '', 'dbname' => 'biller_tests', 'charset' => 'utf8')); }); // Session manager $di->setShared('session', function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); self::authorize(); static::$mock = new \Tests\User(); }
/** * Register the services here to make them general or register in the ModuleDefinition to make them module-specific */ protected function _registerServices() { $di = new \Phalcon\DI\FactoryDefault(); $loader = new \Phalcon\Loader(); /** * We're a registering a set of directories taken from the configuration file */ $loader->registerDirs(array(__DIR__ . '/../apps/library/'))->register(); //Registering a router $di->set('router', function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule("frontend"); $router->add('/:controller/:action', array('module' => 'frontend', 'controller' => 1, 'action' => 2)); $router->add("/login", array('module' => 'backend', 'controller' => 'login', 'action' => 'index')); $router->add("/admin/products/:action", array('module' => 'backend', 'controller' => 'products', 'action' => 1)); $router->add("/products/:action", array('module' => 'frontend', 'controller' => 'products', 'action' => 1)); return $router; }); $this->setDI($di); }
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); }
private function setServices() { $loader = new \Phalcon\Loader(); $loader->registerNamespaces(array('Common' => __DIR__ . '/../components/', 'Common\\Controllers' => __DIR__ . '/../controllers/', 'Common\\Models' => __DIR__ . '/../models/')); $loader->register(); $config = new \Common\Config(); $di = new \Phalcon\DI\FactoryDefault(); $di->set('router', new \Common\Router()); $di->set('url', new \Phalcon\Mvc\Url()); $di->set('db', new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name))); $di->set('session', function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('modelsMetadata', new \Phalcon\Mvc\Model\Metadata\Files(array('metaDataDir' => __DIR__ . '/../cache/models/'))); $this->setDI($di); $this->registerModules(['frontend' => ['className' => 'Frontend\\Module', 'path' => '../apps/frontend/components/Module.php'], 'backend' => ['className' => 'Backend\\Module', 'path' => '../apps/backend/components/Module.php']]); }
<?php //setting default time_zone ini_set('error_reporting', E_ALL); date_default_timezone_set('PRC'); try { // $config = new Phalcon\Config\Adapter\Ini('../app/config/config.ini'); $config = (include __DIR__ . "/../app/config/config.php"); //Register an autoloader $loader = new \Phalcon\Loader(); $loader->registerDirs(array($config->application->controllersDir, $config->application->pluginsDir, $config->application->libraryDir, $config->application->modelsDir))->register(); //Create a DI $di = new Phalcon\DI\FactoryDefault(); //Setup the database service $di->set('db', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name, 'charset' => 'UTF8')); }); //Setup the view component $di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array(".phtml" => 'Phalcon\\Mvc\\View\\Engine\\Php', ".volt" => 'volt')); return $view; }); //Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->resource->baseUri); return $url; }); //Start the session the first time when some component request the session service
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'); }
<?php try { $loader = new Phalcon\Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/'))->register(); $di = new Phalcon\DI\FactoryDefault(); $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "test", "password" => "test", "dbname" => "phalcon_test")); }); $di->set('view', function () { $view = new Phalcon\Mvc\View(); $view->setViewsDir('../app/views/'); return $view; }); $di->set('url', function () { $url = new Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }); $application = new Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Phalcon\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
<?php /** * @author The Phuc * @since 06/01/2016 */ error_reporting(E_ALL); try { /** Define */ define('BASEURL', 'http://phalcon.dev/'); define('CACHE_DATA_ADMIN', '../apps/common/caches/admin'); define('CACHE_DATA_USERS', '../apps/common/caches/users'); define('ADMIN_INFO', serialize(array('name' => 'Thế Phúc', 'email' => '*****@*****.**', 'mailHost' => 'smtp.gmail.com', 'mailPort' => 587, 'mailPassword' => '----'))); /** The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new \Phalcon\DI\FactoryDefault(); /** Registering a router */ $di['router'] = function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule('users'); $router->setDefaultController('index'); $router->setDefaultAction('index'); $adminRoutes = glob(dirname(__DIR__) . "/apps/**/routes/*.php"); foreach ($adminRoutes as $key => $value) { require_once $value; } $router->notFound(array('module' => 'users', 'controller' => 'error', 'action' => 'error404')); $router->removeExtraSlashes(true); return $router; }; /** The URL component is used to generate all kind of urls in the application */ $di->set('url', function () {
<?php use Phalcon\Session\Adapter\Files as Session; use Phalcon\Forms\Manager as FormsManager; $config = (require __DIR__ . '/config.php'); $di = new \Phalcon\DI\FactoryDefault(); $di['db'] = ['className' => '\\Phalcon\\Db\\Adapter\\Pdo\\Mysql', 'arguments' => [['type' => 'parameter', 'value' => $config->database->toArray()]]]; $di['router'] = function () use($config) { return require __DIR__ . '/routes.php'; }; $di['url'] = function () use($config, $di) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }; $di['volt'] = function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $voltOptions = !empty($config->volt) ? $config->volt->toArray() : []; $volt->setOptions(array_merge(['compiledPath' => __DIR__ . '/../cache/views/volt/', 'compiledSeparator' => '-'], $voltOptions)); return $volt; }; $di['view'] = function () use($config, $di) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir)->registerEngines(['.volt' => 'volt']); return $view; }; $di['cookies'] = function () { $cookies = new \Phalcon\Http\Response\Cookies(); $cookies->useEncryption(false); return $cookies; };
<?php try { $config = new Phalcon\Config\Adapter\Ini('../app/config/configuration.ini'); //Register an autoloader $loader = new \Phalcon\Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/', '../app/forms/', '../app/views/', '../app/plugins/', '../app/wrappers/')); $loader->registerNamespaces(array('Silar\\Misc' => '../app/misc/'), true); $loader->register(); //Create a DI $di = new Phalcon\DI\FactoryDefault(); //Registering Volt as template engine $di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir('../app/views/'); $view->registerEngines(array(".volt" => 'Phalcon\\Mvc\\View\\Engine\\Volt')); return $view; }); //Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/silar/'); return $url; }); $di->setShared('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('router', function () { $router = new \Phalcon\Mvc\Router\Annotations();
<?php $env = new \Phalcon\Config\Adapter\Ini('../config/env.ini'); $server = $_SERVER['SERVER_NAME']; foreach ($env->envs as $file => $host) { if ($server === $host) { $config = new \Phalcon\Config\Adapter\Ini('../config/config_' . $file . '.ini'); } } $routers = new \Phalcon\Config\Adapter\Ini('../config/router.ini'); $di = new \Phalcon\DI\FactoryDefault(); $loader = new \Phalcon\Loader(); if (!empty($config->library)) { foreach ($config->library as $name => $patch) { $namespace[$name] = '../' . $config->app->library . $patch; } } $loader->registerNamespaces($namespace); $loader->register(); $di->setShared('config', function () use($config) { return $config; }); $di->setShared('crypt', function () use($config) { $crypt = new \Phalcon\Crypt(); $crypt->setKey($config->auth->cookie_hash); return $crypt; }); $di->setShared('cookies', function () { $cookies = new \Phalcon\Http\Response\Cookies(); return $cookies; });
<?php try { //Enregistrement d'un autoloader pour premettre l'inclusion auto des fichiers de classe $loader = new \Phalcon\Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/'))->register(); //DI est le service responsable de l'injection de dépendance des services Phalcon utilisés $di = new Phalcon\DI\FactoryDefault(); //Configuration des vues $di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir('../app/views/'); return $view; }); //Configuration de l'URL de base $di->set('url', function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/TD1/firstPhalcon/'); return $url; }); //Interception de la requête pour routage et dispatching $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Phalcon\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
<?php ini_set('error_reporting', E_ALL & ~E_NOTICE); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); date_default_timezone_set('Europe/Kiev'); try { $config = new Phalcon\Config\Adapter\Ini('../config/app.ini'); $loader = new \Phalcon\Loader(); $loader->registerDirs(array($config->application->controllersDir, $config->application->pluginsDir, $config->application->libraryDir, $config->application->modelsDir))->register(); //Create a DI $di = new Phalcon\DI\FactoryDefault(); //Set XML Views Config $di->set('func_view', function () use($config) { return array("config" => $config->func_views->path, "dir" => $config->func_views->dir); }); $di->set('main_menu_items', function () use($config) { return array("config" => $config->main_menu_items->path, "dir" => $config->main_menu_items->dir); }); $di->set('action_menu_items', function () use($config) { return array("config" => $config->action_menu_items->path, "dir" => $config->action_menu_items->dir); }); $di->set('resource_strings', function () use($config) { return array("config" => $config->resource_strings->path); }); $di->set('faker', function () use($config) { return array("config" => $config->faker->path); }); $di->set('lang', function () use($config) { return array("default_lang" => $config->lang->default); });
public function build() { $options = $this->_options; $path = ''; if (isset($this->_options['directory'])) { if ($this->_options['directory']) { $path = $this->_options['directory'] . '/'; } } $name = $options['name']; $config = $this->_getConfig($path); if (!isset($config->database->adapter)) { throw new BuilderException("Adapter was not found in the config. Please specify a config varaible [database][adapter]"); } $adapter = ucfirst($config->database->adapter); $this->isSupportedAdapter($adapter); $di = new \Phalcon\DI\FactoryDefault(); $di->set('db', function () use($adapter, $config) { $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; $connection = new $adapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->name)); return $connection; }); if (isset($config->application->modelsDir)) { $options['modelsDir'] = $path . $config->application->modelsDir; } else { throw new BuilderException("The builder is unable to know where is the views directory"); } if (isset($config->application->controllersDir)) { $options['controllersDir'] = $path . $config->application->controllersDir; } else { throw new BuilderException("The builder is unable to know where is the controllers directory"); } if (isset($config->application->viewsDir)) { $options['viewsDir'] = $path . $config->application->viewsDir; } else { throw new BuilderException("The builder is unable to know where is the views directory"); } $options['manager'] = $di->getShared('modelsManager'); $options['className'] = Text::camelize($options['name']); $options['fileName'] = Text::uncamelize($options['className']); $modelBuilder = new \Phalcon\Builder\Model(array('name' => $name, 'schema' => $options['schema'], 'className' => $options['className'], 'fileName' => $options['fileName'], 'genSettersGetters' => $options['genSettersGetters'], 'directory' => $options['directory'], 'force' => $options['force'])); $modelBuilder->build(); $modelClass = Text::camelize($name); if (!class_exists($modelClass)) { require $config->application->modelsDir . '/' . $modelClass . '.php'; } $entity = new $modelClass(); $metaData = $di->getShared('modelsMetadata'); $attributes = $metaData->getAttributes($entity); $dataTypes = $metaData->getDataTypes($entity); $identityField = $metaData->getIdentityField($entity); $primaryKeys = $metaData->getPrimaryKeyAttributes($entity); $setParams = array(); $selectDefinition = array(); $relationField = ''; $single = $name; $options['name'] = strtolower(Text::camelize($single)); $options['plural'] = str_replace('_', ' ', $single); $options['single'] = str_replace('_', ' ', $single); $options['entity'] = $entity; $options['theSingle'] = $single; $options['singleVar'] = $single; $options['setParams'] = $setParams; $options['attributes'] = $attributes; $options['dataTypes'] = $dataTypes; $options['primaryKeys'] = $primaryKeys; $options['identityField'] = $identityField; $options['relationField'] = $relationField; $options['selectDefinition'] = $selectDefinition; $options['autocompleteFields'] = array(); $options['belongsToDefinitions'] = array(); //Build Controller $this->_makeController($path, $options); //View layouts $this->_makeLayouts($path, $options); //View index.phtml $this->_makeViewIndex($path, $options); //View search.phtml $this->_makeViewSearch($path, $options); //View new.phtml $this->_makeViewNew($path, $options); //View edit.phtml $this->_makeViewEdit($path, $options); return true; }
<?php error_reporting(E_ALL); //Test Suite bootstrap include __DIR__ . "/../vendor/autoload.php"; define('TESTS_ROOT_DIR', dirname(__FILE__)); define('APP_ROOT', TESTS_ROOT_DIR . '/fixtures'); $configArray = (require_once TESTS_ROOT_DIR . '/config.php'); $_SERVER['HTTP_HOST'] = 'vegas.dev'; $_SERVER['REQUEST_URI'] = '/'; $config = new \Phalcon\Config($configArray); $di = new Phalcon\DI\FactoryDefault(); $di->set('config', $config); $di->set('collectionManager', function () use($di) { return new \Phalcon\Mvc\Collection\Manager(); }, true); $di->set('collectionManager', function () { return new \Phalcon\Mvc\Collection\Manager(); }); $view = new \Phalcon\Mvc\View(); $view->registerEngines(array('.volt' => function ($this, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($this, $di); $volt->setOptions(array('compiledPath' => TESTS_ROOT_DIR . '/fixtures/cache/', 'compiledSeparator' => '_')); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); $di->set('view', $view); $di->set('mongo', function () use($config) { $mongo = new \MongoClient(); return $mongo->selectDb($config->mongo->db); }, true); $di->set('modelManager', function () use($di) {
<?php error_reporting(E_ALL); //Test Suite bootstrap include __DIR__ . "/../vendor/autoload.php"; define('TESTS_ROOT_DIR', dirname(__FILE__)); $configArray = (require_once dirname(__FILE__) . '/fixtures/app/config/config.php'); $config = new \Phalcon\Config($configArray); $di = new \Phalcon\DI\FactoryDefault(); $di->set('config', $config); require_once dirname(__FILE__) . '/fixtures/app/services/SqliteServiceProvider.php'; (new \SqliteServiceProvider())->register($di); \Phalcon\DI::setDefault($di);
<?php try { // Регистрация автозагрузчика $loader = new Phalcon\Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/'))->register(); // Создание DI $di = new Phalcon\DI\FactoryDefault(); // Настраиваем сервис для работы с БД $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "root", "password" => "root", "dbname" => "phalcon")); }); // Настраиваем компонент View $di->set('view', function () { $view = new Phalcon\Mvc\View(); $view->setViewsDir('../app/views/'); return $view; }); // Обработка запроса $application = new Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (Phalcon\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
<?php error_reporting(E_ALL); try { /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new \Phalcon\DI\FactoryDefault(); /** * Registering a router */ $di['router'] = function () { $router = new \Phalcon\Mvc\Router(false); $router->add('/admin', array('module' => 'backend', 'controller' => 'index', 'action' => 'index')); $router->add('/index', array('module' => 'frontend', 'controller' => 'index', 'action' => 'index')); $router->add('/', array('module' => 'frontend', 'controller' => 'index', 'action' => 'index')); return $router; }; /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/mvc/multiple-shared-layouts/'); return $url; }); /** * Start the session the first time some component request the session service */ $di->set('session', function () { $session = new \Phalcon\Session\Adapter\Files();
protected function _registerServices() { $di = new \Phalcon\DI\FactoryDefault(); $loader = new \Phalcon\Loader(); $loader->registerDirs(array(FOLDER_PROJECT . '/apps/library/', FOLDER_PROJECT . '/apps/backend/models', FOLDER_PROJECT . '/apps/frontend/models'))->register(); //usando autoloader do composer para carregar as depêndencias instaladas via composer require_once FOLDER_PROJECT . 'vendor/autoload.php'; $di->set('router', function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule("frontend"); $router->add('/:controller/:action', array('module' => 'frontend', 'controller' => 1, 'action' => 2)); $router->add('/:controller/:action', array('module' => 'backend', 'controller' => 1, 'action' => 2)); $router->add("/admin", array('module' => 'backend', 'controller' => 'index', 'action' => 'index')); $router->add("/editor", array('module' => 'frontend', 'controller' => 'index', 'action' => 'index')); $router->add("/index/:action", array('controller' => 'index', 'action' => 1)); return $router; }); $di->set("libMail", function () { return new Multiple\Library\Mail(); }); /** * Caso exista o arquivo de configuração config.ini coleta os dados existentes nele e * conecta com o banco de dados */ if (file_exists('../apps/config/config.ini')) { $config = new \Phalcon\Config\Adapter\Ini('../apps/config/config.ini'); //Seta a conexão com o banco de dados $di->set('db', function () use($config) { $dbclass = 'Phalcon\\Db\\Adapter\\Pdo\\' . $config->database->adapter; return new $dbclass(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name, "charset" => 'utf8')); }); } $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'); } $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); }