/** * Registers the module-only services * * @param Phalcon\DI $di */ public function registerServices($di) { /** * Read configuration */ $config = (include __DIR__ . "/config/config.php"); $di['dispatcher'] = function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace("Test\\Backend\\Controllers"); return $dispatcher; }; //Register Volt as a service $di['voltService'] = function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => "../cache/compiled-templates/", "compiledExtension" => ".compiled", "compileAlways" => true)); return $volt; }; /** * Setting up the view component */ $di['view'] = function () { $view = new View(); $view->setViewsDir(__DIR__ . '/views/default/'); $view->registerEngines(array(".volt" => 'voltService')); return $view; }; /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { return new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); }; }
/** * 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); }
/** * * Register the services here to make them module-specific * */ public function registerServices($di) { // get bootstrap obj $bootstrap = $di->get('bootstrap'); // get config class name $confClass = $bootstrap->getConfClass(); // module config $mConfPath = __DIR__ . '/confs/' . PHALCON_ENV . '.' . PHALCON_CONF_TYPE; if (!is_file($mConfPath)) { throw new \Phalcon\Config\Exception("Module config file not exist, file position: {$mConfPath}"); } if (PHALCON_CONF_TYPE == 'ini') { $mConfig = new $confClass($mConfPath); } else { if (PHALCON_CONF_TYPE == 'php') { $mConfig = new $confClass(require_once $mConfPath); } } // global config $gConfig = $di->get('config'); // merge module config and global config, module's will override global's $gConfig->merge($mConfig); // set config back $di->set('config', $gConfig); // registering a dispatcher $di->set('dispatcher', function () use($di) { $evtManager = $di->getShared('eventsManager'); $evtManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) { switch ($exception->getCode()) { case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND: $dispatcher->forward(array('module' => 'sample', 'controller' => 'error', 'action' => 'show404')); return false; } }); $acl = new \BullSoft\Sample\Plugins\Acl($di, $evtManager); $evtManager->attach('dispatch', $acl); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($evtManager); $dispatcher->setDefaultNamespace("BullSoft\\Sample\\Controllers\\"); return $dispatcher; }); // set view with volt $di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . '/views/'); $view->registerEngines(array(".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => $di->get('config')->view->compiledPath, "compiledExtension" => $di->get('config')->view->compiledExtension, "compileAlways" => (bool) $di->get('config')->application->debug)); $compiler = $volt->getCompiler(); $compiler->addExtension(new \BullSoft\Volt\Extension\PhpFunction()); return $volt; })); return $view; }); }
public function setVoltTemplates() { $this->set('voltService', function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(['compiledPath' => '../cache/compiledTpl/', 'compiledExtension' => '.cmp', 'compileAlways' => false]); // Функции для отображения даты (добавлено '->sec' для даты MongoDate) //$volt->getCompiler()->addFunction('shortDate', function($date) {return 'date("d.m.Y",' . $date . '->sec)';}); return $volt; }); }
protected function registerView() { $this->di->set('volt.service', function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => ROOT_PATH . "/public/views/", "compiledExtension" => ".compiled", 'compiledSeparator' => '_', 'stat' => true, 'compileAlways' => true)); return $volt; }); $this->di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(APP_PATH . '/views/'); $view->registerEngines(array(".phtml" => 'volt.service')); return $view; }); }
private static function cgiRegister() { $di = get_app_di(); $config = self::getConfig(); self::registCommonService($di, $config); $di->setShared('router', function () { $router = new \Phalcon\Mvc\Router(); $router->removeExtraSlashes(true); $router->add('/:controller/:action/:params', array('controller' => 1, 'action' => 2, 'params' => 3)); return $router; }); $di->setShared('dispatcher', function () { $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin()); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace("App\\Controllers\\"); return $dispatcher; }); $di->setShared('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->view->templatePath); $view->registerEngines(array('.html' => function ($view, $di) { $config = $di->get('config'); $compiledPath = $config->view->compiledPath; if (!file_exists($compiledPath)) { mkdir($compiledPath, 0744, true); } $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => $compiledPath, 'compiledExtension' => $config->view->compiledExtension, 'compileAlways' => isset($config->view->compileAlways) ?: false)); $compiler = $volt->getCompiler(); $compiler->addExtension(new VoltExtension()); $autoEscape = isset($config->view->autoEscape) ?: true; ClassUtil::modifyPrivateProperties($compiler, array('_autoescape' => $autoEscape)); return $volt; })); return $view; }); $di->setShared('elements', function () { return new ElementsPlugin(); }); }
public function registerServices(\Phalcon\DiInterface $di = NULL) { $config = $di->get('config'); $di->set('dispatcher', function () use($di) { $eventsManager = $di->getShared('eventsManager'); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace($this->namespace . '\\Controllers\\'); return $dispatcher; }); if (file_exists('../' . $config->app->apps . $this->moduleName . '/config/routers.ini')) { $router = $di->get('router'); $routers = new \Phalcon\Config\Adapter\Ini('../' . $config->app->apps . $this->moduleName . '/config/routers.ini'); if (!empty($routers)) { foreach ($routers as $name => $rule) { $rule->module = $this->moduleName; $pattern = $rule->pattern; unset($rule->pattern); $router->add($pattern, $rule->toArray())->setName($name); } } $router->handle(); } $di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir('../' . $config->app->apps . $this->moduleName . '/' . $config->app->views); $view->registerEngines(array('.html' => function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => '../' . $config->app->apps . $this->moduleName . '/cache/volt/', 'compiledExtension' => '.php', 'compileAlways' => true, 'compiledSeparator' => '_')); return $volt; })); return $view; }); $di->set('flashSession', function () { return new \Phalcon\Flash\Session(array('error' => 'alert alert-warning alert-small', 'success' => 'alert alert-success', 'notice' => 'alert alert-info')); }); $di->set('flash', function () { return new \Phalcon\Flash\Direct(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info')); }); }
/** * Register specific services for the module */ public function registerServices(\Phalcon\DiInterface $dependencyInjector) { /** * Read configuration */ $config = (require_once MODULES_DIR . $this->module_name . DS . "config" . DS . "config.php"); //Registering a dispatcher $dependencyInjector->set('dispatcher', function () { $dispatcher = new \Phalcon\Mvc\Dispatcher(); //Attach a event listener to the dispatcher $eventManager = new \Phalcon\Events\Manager(); //$eventManager->attach('dispatch', new \Acl($this->module_name)); $dispatcher->setEventsManager($eventManager); $dispatcher->setDefaultNamespace("Mod\\ModMan\\Controllers\\"); return $dispatcher; }); /** * Setting up the view component */ $dependencyInjector->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->module->viewsDir); $view->setViewsDir(MODULES_DIR . $this->module_name . DS . 'views' . DS); $view->setLayoutsDir(MODULES_DIR . $this->module_name . DS . 'layouts' . DS); //$view->setTemplateAfter('index'); $view->registerEngines(array('.volt' => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => MODULES_DIR . $this->module_name . DS . 'views' . DS . '_compiled' . DS, 'stat' => true, 'compileAlways' => true)); return $volt; })); return $view; }); /** * Database connection is created based in the parameters defined in the configuration file * http://stackoverflow.com/questions/22197678/how-to-connect-multiple-database-in-phalcon-framework */ $dependencyInjector->set('db', function () use($config) { return new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); }); }
/** * Generate a new View object with preset parameters. * * @param array $options * @param \Phalcon\DiInterface $di * @return \Phalcon\Mvc\View */ public static function getView($options = array(), \Phalcon\DiInterface $di = null) { if ($di == null) { $di = \Phalcon\Di::getDefault(); } $defaults = array('base_dir' => DF_INCLUDE_BASE . '/', 'views_dir' => 'modules/frontend/views/scripts/', 'partials_dir' => '', 'layouts_dir' => '../../../../templates/', 'layout' => 'main'); $options = array_merge($defaults, (array) $options); $view = new \Phalcon\Mvc\View(); $view->setDI($di); $eventsManager = new \Phalcon\Events\Manager(); $view->setEventsManager($eventsManager); // Base directory from which all views load. $view->setBasePath($options['base_dir']); $view->setViewsDir($options['views_dir']); // Relative path of main templates. $view->setLayoutsDir($options['layouts_dir']); $view->setTemplateAfter($options['layout']); // Use present directory for partials by default. $view->setPartialsDir($options['partials_dir']); // Register template engines. $view->registerEngines(array(".phtml" => 'Phalcon\\Mvc\\View\\Engine\\Php', ".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => function ($templatePath) { $find_replace = array(DF_INCLUDE_BASE => '', '/modules/' => '', '/views/scripts/' => '_', '/' => '_'); $templatePath = str_replace(array_keys($find_replace), array_values($find_replace), $templatePath); return DF_INCLUDE_CACHE . '/volt_' . $templatePath . '.compiled.php'; })); $compiler = $volt->getCompiler(); $compiler->addFunction('helper', function ($resolvedArgs, $exprArgs) use($di) { return '$this->viewHelper->handle(' . $resolvedArgs . ')'; }); return $volt; })); // Register global escaper. $view->setVar('e', new \Phalcon\Escaper()); return $view; }
use Phalcon\Loader; use Phalcon\Mvc\View; use Phalcon\Mvc\Application; use Phalcon\DI\FactoryDefault; use Phalcon\Mvc\Url as UrlProvider; use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter; try { $loader = new Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/'))->register(); $di = new FactoryDefault(); $di->set('view', function () { $view = new View(); $view->setViewsDir('../app/views/'); $view->registerEngines(['.volt' => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(['compiledPath' => '../app/cache/']); return $volt; }]); return $view; }); $di->set('url', function () { $url = new UrlProvider(); $url->setBaseUri('/'); return $url; }); $application = new Application($di); echo $application->handle()->getContent(); } catch (\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
$di->set('router', require APP_PATH . '/app/config/routes.php'); //MetaData $di->set('modelsMetadata', function () { if (function_exists('apc_store')) { return new Phalcon\Mvc\Model\MetaData\Apc(); } else { return new Phalcon\Mvc\Model\MetaData\Memory(array('metaDataDir' => APP_PATH . "/app/compiled-templates/")); } }); // Setting up the view component (seems to be required even when not used) $di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array(".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => APP_PATH . "/app/compiled-templates/", "compiledExtension" => ".compiled", "compiledSeparator" => '_')); return $volt; })); return $view; }); // Setting up the database connection $di->set('db', function () use($config) { $database = $config->database; return new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => $database->host, 'username' => $database->username, 'password' => $database->password, 'dbname' => $database->name, 'options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))); }); // Setting up the mongodb connection $di->set('mongo', function () use($config) { $mongodbConfig = $config->mongodb; $mongo = new \MongoClient($mongodbConfig->url); return $mongo->{$mongodbConfig->db}; });
$di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . $config->application->viewsDir); $view->registerEngines(array(".volt" => 'volt')); return $view; }); $di->set('viewCache', function () { // Кэширование данных на сутки по умолчанию $frontCache = new Phalcon\Cache\Frontend\Output(array("lifetime" => 86400)); // Настройки соединения с Memcached $cache = new Phalcon\Cache\Backend\Apc($frontCache, array()); return $cache; }); $di->set('volt', function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => "../cache/volt/")); return $volt; }, true); $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, "options" => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))); }); /** * 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(); } return new Phalcon\Mvc\Model\Metadata\Memory();
return $router; }); $di->set('url', function () { $url = new Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }); $di->set('view', function () use($config) { $view = new Phalcon\Mvc\View(); $view->setViewsDir(APP_PATH . $config->application->viewsDir); $view->registerEngines(array('.volt' => 'volt')); return $view; }); $di->set('volt', function ($view, $di) { $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => APP_PATH . 'cache/volt/')); return $volt; }, true); $di->setShared('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('tag', function () { return new Phalcon\Tag(); }); $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->dbname, 'charset' => 'utf8')); }); $di->set('cookies', function () { return new Phalcon\Http\Response\Cookies();
$security->setWorkFactor(13); $security->setDefaultHash(Phalcon\Security::CRYPT_BLOWFISH_Y); return $security; }; $di['redis'] = function () use($config) { $redis = new \Redis(); $redis->connect($config->redis->host, $config->redis->port); return $redis; }; $di['url'] = function () use($config, $di) { $url = new \Phalcon\Mvc\Url(); return $url; }; $di['voltService'] = function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); if (!is_dir($config->view->cache->dir)) { mkdir($config->view->cache->dir); } $volt->setOptions(array("compiledPath" => $config->view->cache->dir, "compiledExtension" => ".compiled", "compileAlways" => true)); return $volt; }; $di['logger'] = function () { $file = __DIR__ . "/../logs/" . date("Y-m-d") . ".log"; $logger = new Logger($file, array('mode' => 'w+')); return $logger; }; $di['cache'] = function () use($di, $config) { $frontend = new \Phalcon\Cache\Frontend\Igbinary(array('lifetime' => 3600 * 24)); $cache = new \Phalcon\Cache\Backend\Redis($frontend, array('redis' => $di['redis'], 'prefix' => $config->application->name . ':')); return $cache; };
$redis = new \Redis(); $redis->connect($config->redis->host, $config->redis->port); return $redis; }; //Overwrite for backwards compatibility $di['url'] = function () use($config) { $url = new \Phalcon\Mvc\Url(); return $url; }; //Custom DI component to use for the Volt template engine $di['voltService'] = function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); if (!is_dir($config->view->cache->dir)) { mkdir($config->view->cache->dir); } $volt->setOptions(array('compiledPath' => $config->view->cache->dir, 'compiledExtension' => '.compiled', 'compileAlways' => true)); return $volt; }; //Log errors in the logs folder $di['logger'] = function () { $file = __DIR__ . '/../logs/' . date('Y-m-d') . '.log'; $logger = new Logger($file, array('mode' => 'w+')); return $logger; }; $di['cache'] = function () use($di, $config) { $frontend = new \Phalcon\Cache\Frontend\Igbinary(array('lifetime' => 3600 * 24)); $cache = new \Phalcon\Cache\Backend\Redis($frontend, array('redis' => $di['redis'], 'prefix' => $config->application->name . ':')); return $cache; }; $di['db'] = function () use($config) { $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "options" => array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'", \PDO::ATTR_CASE => \PDO::CASE_LOWER, \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, \PDO::ATTR_PERSISTENT => true)));
$di->setShared('session', function () use($config) { session_set_cookie_params($config->app->session_lifetime); if ($config->app->debug != 1) { ini_set('session.cookie_secure', '1'); ini_set('session.cookie_httponly', '1'); } $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->setShared('view', function () use($config) { $view = new Phalcon\Mvc\View\Simple(); $view->setViewsDir(ROOTDIR . '/app/views/'); $view->registerEngines(array('.phtml' => function ($view) use($config) { $volt = new Phalcon\Mvc\View\Engine\Volt($view); $volt->setOptions(array('compiledPath' => ROOTDIR . '/tmp/volt/', 'compiledExtension' => '.php', 'compiledSeparator' => '_', 'compileAlways' => true)); $compiler = $volt->getCompiler(); $compiler->addFunction('recaptcha_get_html', function () use($config) { return "'" . recaptcha_get_html($config->captcha->pub, null, true) . "'"; }); return $volt; })); return $view; }); $di->setShared('db', function () use($config) { $db = new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->toArray()); $db->execute('SET NAMES UTF8', array()); return $db; }); $di->setShared('modelsMetadata', function () use($config) { if ($config->app->cache_apc) {
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; }; $di['assets'] = function () { return require_once __DIR__ . '/assets.php'; };
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo; use Phalcon\Session\Adapter\Files as Session; use Phalcon\Flash\Session as FlashSession; try { // Register an autoloader $loader = new Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/'))->register(); // Create a DI $di = new FactoryDefault(); // Setup the view component $di->set('view', function () { $view = new View(); $view->setViewsDir('../app/views/'); $view->registerEngines(array(".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => '../app/views/compiled/', 'compileAlways' => true)); $compiler = $volt->getCompiler(); $compiler->addFilter('removeDots', function ($resolvedArgs, $exprArgs) { return 'str_replace(".", "", ' . $resolvedArgs . ')'; }); return $volt; })); return $view; }); // Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function () { $url = new UrlProvider(); $url->setBaseUri('/'); return $url; }); $di->set('router', function () {
<?php use Phalcon\Mvc\Url as UrlResolver; use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter; $di = new Phalcon\DI\FactoryDefault(); $di->set('config', $config); $di->set('db', function () use($config) { $connection = new Phalcon\Db\Adapter\Pdo\Mysql($config->database->toArray()); return $connection; }); $di->set('view', function () use($config) { $view = new Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_')); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true); $di->set('router', function () { return require __DIR__ . '/routes.php'; }); $di->set('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }, true);
$di->set('url', function () { return new \Phalcon\Mvc\Url(); }, true); /** * Setting up view, use Volt Template Engine */ $di->set('view', function () use($di, $config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(ROOT . DS . 'apps' . DS . SITENAME . DS . 'Views' . DS); $view->registerEngines(array('.volt' => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $compiledPath = ROOT . DS . 'cache' . DS . SITENAME . DS . 'volt' . DS; if (!file_exists($compiledPath)) { mkdir($compiledPath, 0777, true); } $volt->setOptions(array('compiledPath' => $compiledPath, 'compiledExtension' => '.cache', 'compiledSeparator' => '%', 'stat' => true, 'compileAlways' => true)); $compiler = $volt->getCompiler(); $compiler->addFunction('_', function ($resolvedArgs, $exprArgs) use($di) { $translate = $di->get('translate'); return $translate->trans($exprArgs, $resolvedArgs); }); $compiler->addFunction('ng', function ($input) { return '"{{".' . $input . '."}}"'; }); $compiler->addFilter('truncate', function ($resolvedArgs, $exprArgs) { $string = $exprArgs[0]['expr']['value']; $length = (int) $exprArgs[1]['expr']['value']; $end = isset($exprArgs[2]) ? $exprArgs[2]['expr']['value'] : '...'; return "mb_strimwidth({$string}, 0, {$length}, '{$end}', 'UTF-8')"; }); $compiler->addFilter('shift', function ($resolvedArgs, $exprArgs) {
$di->set('acl', function () use($di, $config) { return new Phalcon\Acl\Adapter\Database(array('db' => $di->get('db'), 'roles' => 'roles', 'rolesInherits' => 'roles_inherits', 'resources' => 'resources', 'resourcesAccesses' => 'resources_accesses', 'accessList' => 'access_list')); }, true); $di->set('translate', function () { return new Lininliao\Library\Locale\Translate(SITENAME); }, true); $di->set('simpleView', function () use($di, $config) { $view = new \Phalcon\Mvc\View\Simple(); $view->setDI($di); $view->registerEngines(array('.volt' => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $compiledPath = ROOT . DS . 'cache' . DS . SITENAME . DS . 'volt' . DS; if (!file_exists($compiledPath)) { mkdir($compiledPath, 0777, true); } $volt->setOptions(array('compiledPath' => $compiledPath, 'compiledExtension' => '.cache', 'compiledSeparator' => '%', 'stat' => true, 'compileAlways' => ENVIRONMENT === 'production' ? false : true)); $compiler = $volt->getCompiler(); $compiler->addFunction('_', function ($resolvedArgs, $exprArgs) use($di) { $translate = $di->get('translate'); return $translate->trans($exprArgs, $resolvedArgs); }); return $volt; })); return $view; }, true); $di->set('mail', function () { return new Lininliao\Library\Swift\Mail(); }, true); $console = new \Phalcon\CLI\Console(); $console->setDI($di); $arguments = array();
/** * Prevent CSRF */ $di->setShared('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); /** * Set Flash */ $di->set('flash', function () { return new Phalcon\Flash\Session(array('error' => 'alert alert-dismissable alert-danger', 'success' => 'alert alert-dismissable alert-success', 'notice' => 'alert alert-dismissable alert-info', 'warning' => 'alert alert-dismissable alert-warning')); }); /** * Set flashSession */ $di->set('flashSession', function () { return new Phalcon\Flash\Session(array('error' => 'alert alert-dismissable alert-danger', 'success' => 'alert alert-dismissable alert-success', 'notice' => 'alert alert-dismissable alert-info', 'warning' => 'alert alert-dismissable alert-warning')); }); $di->set('view', function () use($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); $view->setMainView('index'); $view->registerEngines(array('.volt' => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => APP_DIR . 'views' . DS . '_compiled' . DS, 'stat' => true, 'compileAlways' => true)); return $volt; })); return $view; });
public function testVoltCompilerFileOptions() { $di = new Phalcon\DI(); $view = new Phalcon\Mvc\View(); $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => "unit-tests/cache/", "compiledSeparator" => ".", "compiledExtension" => ".compiled")); @unlink('unit-tests/views/test10/index.volt.php'); @unlink('unit-tests/cache/unit-tests.views.test10.index.volt.compiled'); //Render simple view $view->start(); $volt->render('unit-tests/views/test10/index.volt', array('song' => 'Lights'), true); $view->finish(); $path = 'unit-tests/cache/' . phalcon_prepare_virtual_path(realpath("unit-tests/"), ".") . '.views.test10.index.volt.compiled'; $this->assertTrue(file_exists($path)); $this->assertEquals(file_get_contents($path), 'Hello <?php echo $song; ?>!'); $this->assertEquals($view->getContent(), 'Hello Lights!'); }
<?php try { $app = new Phalcon\Mvc\Micro(); // Setting up the database connection $app['db'] = function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(array('dsn' => 'host=localhost;dbname=hello_world;charset=utf8', 'username' => 'benchmarkdbuser', 'password' => 'benchmarkdbpass', 'persistent' => true)); }; // Setting up the view component (seems to be required even when not used) $app['view'] = function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . '/../views/'); $view->registerEngines(array(".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => __DIR__ . "/../compiled-templates/", "compiledExtension" => ".c", "compiledSeparator" => '_')); return $volt; })); return $view; }; $app->map('/json', function () { header("Content-Type: application/json"); echo json_encode(array('message' => 'Hello, World!')); }); // $app->map('/db', function () use($app) { $db = $app['db']; $queries = $app->request->getQuery('queries', null, 1); $worlds = array(); for ($i = 0; $i < $queries; ++$i) { $worlds[] = $db->fetchOne('SELECT * FROM world WHERE id = ' . mt_rand(1, 10000), Phalcon\Db::FETCH_ASSOC); }
$di->set('db', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Postgresql(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('dispatcher', function () use($di) { $eventsManager = $di->getShared('eventsManager'); $security = new Security($di); $eventsManager->attach('dispatch', $security); $dispatcher = new Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); $di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir('../app/views/'); $view->registerEngines(array(".volt" => function ($view, $id) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $id); $volt->setOptions(array('compileAlways' => true)); return $volt; })); return $view; }); $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Phalcon\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
$di->set('dispatcher', function () use($di) { $dispatcher = new Phalcon\Mvc\Dispatcher(); return $dispatcher; }); //Registering a Http\Response $di->set('response', 'Phalcon\\Http\\Response'); //Registering a Http\Request $di->set('request', 'Phalcon\\Http\\Request'); //register filter $di->set('filter', function () { return new \Phalcon\Filter(); }); //register service to run templates $di->set('voltService', function ($view, $di) use($config) { $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => $config->application->templCompDir, "compiledExtension" => ".compiled")); return $volt; }); //set cache engine $di->set('cache', function () { //Cache data for 1 minute $frontCache = new Phalcon\Cache\Frontend\Data(array("lifetime" => 60)); //Memcached connection settings // $cache = new Phalcon\Cache\Backend\File($frontCache, array( // "cacheDir" => "../apps/cache/" //)); // we would use APC cache $cache = new Phalcon\Cache\Backend\Apc($frontCache); return $cache; }); //Registering the view component
}); //Start the session the first time when some component request the session service $di->setShared('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('elements', function () { return new Elements(); }); /** * Setting up volt */ $di->set('volt', function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => $config->cache->voltCacheDir)); return $volt; }, true); //phalcon Case insesitive routing || url:https://forum.phalconphp.com/discussion/1824/case-insesitive-routing-how-to- if (isset($_GET['_url'])) { $_GET['_url'] = strtolower($_GET['_url']); } //setroutes // $di->set('router', function () // { // require __DIR__.'/../app/config/routes.php'; // return $router; // }); $usecdn = $config->resource->useCDN; $di->set('usecdn', function () use($usecdn) { return $usecdn;
return $url; }); //=================================以下为未确认=========================================== /** * 把volt注册成服务,在controller中改变volt默认行为 * example: * 给模板引擎添加unserialize函数 * <code> * $volt = $this->di->get("voltService", array($this->view, $this->di)); * $compiler = $volt->getCompiler(); * $compiler->addFunction('unserialize', 'unserialize'); * </code> */ $di->setShared('voltService', function ($view, $di) use($config) { $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(['compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_', 'compileAlways' => true]); // TODO: 偶尔使用的function不要在这里添加,要在controller中设置 $compiler = $volt->getCompiler(); $compiler->addFunction('current', 'current'); $compiler->addFunction('explode', 'explode'); $compiler->addFunction('strpos', 'strpos'); $compiler->addFunction('basename', 'basename'); $compiler->addFunction('array_shift', 'array_shift'); $compiler->addFunction('array_push', 'array_push'); $compiler->addFilter('substr_replace', 'substr_replace'); return $volt; }); /** * Setting up the view component */ $di->setShared('view', function () use($config) {
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) { return new \Phalcon\Mvc\Model\Manager(); }, true); $di->set('db', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->toArray()); }, true); Phalcon\DI::setDefault($di);
$loader = new \Phalcon\Loader(); $loader->registerDirs(array('../app/controllers/', '../app/models/', '../app/forms/', '../app/views/', '../app/plugins/', '../app/validators/', '../app/wrappers/')); $loader->registerNamespaces(array('Sigmamovil\\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" => 'volt')); return $view; }); $di->setShared('volt', function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compileAlways" => true, "compiledPath" => "../app/compiled-templates/", 'stat' => true)); $compiler = $volt->getCompiler(); return $volt; }); $di->set('logger', function () { // Archivo de log return new \Phalcon\Logger\Adapter\File("../app/logs/debug.log"); }); $urlManager = new \Sigmamovil\Misc\UrlManager($config); $di->set('urlManager', $urlManager); //Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function () use($urlManager) { $url = new \Phalcon\Mvc\Url(); $uri = $urlManager->get_base_uri(); // Adicionar / al inicio y al final if (substr($uri, 0, 1) != '/') {