/** * Registers the module-only services * * @param Phalcon\DI $di */ public function registerServices(\Phalcon\DiInterface $di) { /** * Read configuration */ /** * Setting up the view component */ $config = $this->config; $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->backendViewsDir); $view->registerEngines(array(".volt" => 'volt')); return $view; }, true); /** * Setting up volt */ $di->set('volt', function ($view, $di) use($config) { $volt = new Volt($view, $di); $volt->setOptions(array("compiledPath" => APP_PATH . "/app/cache/volt/", "compiledSeparator" => "_", "compileAlways" => $config->application->debug)); $volt->getCompiler()->addFunction('tr', function ($key) { return "messetool\\Modules\\Modules\\Backend\\Controllers\\ControllerBase::translate({$key})"; }); $volt->getCompiler()->addFunction('number_format', function ($resolvedArgs) { return 'number_format(' . $resolvedArgs . ')'; }); $volt->getCompiler()->addFunction('linkAllowed', function ($args) { return "messetool\\Acl\\Acl::linkAllowed({$args})"; }); return $volt; }, true); }
public function addFunction(Extension\ExFunction $extension) { $this->volt->getCompiler()->addFunction($extension->getName(), function () use($extension) { $this->view->setVar('func_extension_' . $extension->getName(), $extension); $extension->setParams(func_get_args()); return '$this->getView()->getVar(\'func_extension_' . $extension->getName() . '\')->call();'; }); }
/** * Register specific services for the module * @param \Phalcon\DiInterface $di */ public function registerServices(DiInterface $di) { $config = $this->_config; $configShared = $di->get('config'); $vDI = $di; //Registering a dispatcher $di->set('dispatcher', function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('Cnab'); return $dispatcher; }); //Registering the view component $di->set('volt', function ($view, $vDI) use($config, $configShared) { $volt = new Volt($view, $vDI); $volt->setOptions(array('compiledPath' => $configShared->volt->path, 'compiledExtension' => $configShared->volt->extension, 'compiledSeparator' => $configShared->volt->separator, 'stat' => (bool) $configShared->volt->stat)); $compiler = $volt->getCompiler(); //Add funcao $compiler->addFunction('is_a', 'is_a'); return $volt; }); /** * Configura o serviço de view */ $di->set('view', function () use($config, $vDI) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => 'volt')); return $view; }); return $di; }
/** * Create view instance. * If no events manager provided - events would not be attached. * * @param DIBehaviour $di DI. * @param Config $config Configuration. * @param string|null $viewsDirectory Views directory location. * @param Manager|null $em Events manager. * * @return View */ public static function factory($di, $config, $viewsDirectory = null, $em = null) { $view = new View(); $volt = new Volt($view, $di); $volt->setOptions(["compiledPath" => $config->application->view->compiledPath, "compiledExtension" => $config->application->view->compiledExtension, 'compiledSeparator' => $config->application->view->compiledSeparator, 'compileAlways' => $config->application->debug && $config->application->view->compileAlways]); $compiler = $volt->getCompiler(); $compiler->addExtension(new Extension()); $view->registerEngines([".volt" => $volt])->setRenderLevel(View::LEVEL_ACTION_VIEW)->restoreViewDir(); if (!$viewsDirectory) { $view->setViewsDir($viewsDirectory); } // Attach a listener for type "view". if ($em) { $em->attach("view", function ($event, $view) use($di, $config) { if ($config->application->profiler && $di->has('profiler')) { if ($event->getType() == 'beforeRender') { $di->get('profiler')->start(); } if ($event->getType() == 'afterRender') { $di->get('profiler')->stop($view->getActiveRenderPath(), 'view'); } } if ($event->getType() == 'notFoundView') { throw new Exception('View not found - "' . $view->getActiveRenderPath() . '"'); } }); $view->setEventsManager($em); } return $view; }
public function getCompiler() { // Load macros: if (empty($this->_compiler)) { parent::getCompiler(); $this->partial('macros'); } $compiler = parent::getCompiler(); // View filters: $compiler->addFilter('merge', 'array_merge'); $compiler->addFilter('md5', 'md5'); $compiler->addFilter('split', function ($resolvedArgs, $exprArgs) { $a = explode(',', $resolvedArgs); $cmd = 'explode(' . trim($a[1]) . ', ' . $a[0] . ')'; return $cmd; }); $compiler->addFilter('trans', function ($resolvedArgs, $exprArgs) { $a = explode(',', $resolvedArgs); return '$this->di->getTrans()->query(' . $a[0] . (count($a) > 1 ? ',' . $a[1] : '') . ')'; }); $compiler->addFilter('date', function ($resolvedArgs, $exprArgs) { $a = explode(',', $resolvedArgs); return 'date(' . $a[1] . ', strtotime(' . $a[0] . '))'; }); $compiler->addFunction('is_granted', function ($args) { return '$this->di->getUser()->isGranted(' . $args . ')'; }); $compiler->addFunction('render', function ($args) { return 'file_get_contents(sprintf(\'%s://%s\', $_SERVER[\'REQUEST_SCHEME\'], $_SERVER[\'HTTP_HOST\']).' . $args . ')'; }); $compiler->addFunction('square', function ($arg) { return $arg . ' * ' . $arg; }); return $compiler; }
/** * register custom volt function to use in frontend * * @param $view * @param array $functions */ public static function registerViewFunctions(Volt &$view, array $functions = []) { $compiler = $view->getCompiler(); foreach ($functions as $name => $body) { $compiler->addFunction($name, $body); } }
/** * Create view instance. * If no events manager provided - events would not be attached. * * @param DIBehaviour $di DI. * @param Config $config Configuration. * @param string $viewsDirectory Views directory location. * @param Manager|null $em Events manager. * * @return View */ public static function factory($di, $config, $viewsDirectory, $em = null) { $view = new PhView(); $volt = new PhVolt($view, $di); $volt->setOptions(["compiledPath" => $config->global->view->compiledPath, "compiledExtension" => $config->global->view->compiledExtension, 'compiledSeparator' => $config->global->view->compiledSeparator, 'compileAlways' => $config->global->view->compileAlways]); $compiler = $volt->getCompiler(); $compiler->addExtension(new EnViewExtension()); $compiler->addFilter('floor', 'floor'); $compiler->addFunction('range', 'range'); $compiler->addFunction('in_array', 'in_array'); $compiler->addFunction('count', 'count'); $compiler->addFunction('str_repeat', 'str_repeat'); $view->registerEngines(['.volt' => $volt])->setRenderLevel(PhView::LEVEL_ACTION_VIEW)->setViewsDir($viewsDirectory); // Attach a listener for type "view". if ($em) { $em->attach("view", function ($event, $view) use($di, $config) { if ($config->global->profiler && $di->has('profiler')) { if ($event->getType() == 'beforeRender') { $di->get('profiler')->start(); } if ($event->getType() == 'afterRender') { $di->get('profiler')->stop($view->getActiveRenderPath(), 'view'); } } if ($event->getType() == 'notFoundView') { throw new Exception('View not found - "' . $view->getActiveRenderPath() . '"'); } }); $view->setEventsManager($em); } $di->set('view', $view); return $view; }
public function getCompiler() { if (empty($this->_compiler)) { parent::getCompiler(); // add macros that need initialized before parse time $this->partial("macros/url"); } return parent::getCompiler(); }
private function registerVolt(&$view, $di, $config) { $view->registerEngines([".volt" => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $options = ['compileAlways' => $this->getConfig('app')->debug, 'compiledPath' => $config['engine']['volt']['cache'], 'compiledSeparator' => '_']; $volt->setOptions($options); $compiler = $volt->getCompiler(); return $volt; }]); return; }
/** * Registers services related to the module * * @param DiInterface $di */ public function registerServices(DiInterface $di) { /** * Read configuration */ $config = (include APP_PATH . "/apps/backend/config/config.php"); /** * Setting up the view component */ $di['view'] = function () use($config) { $view = new View(); $view->setViewsDir(__DIR__ . '/views/'); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => __DIR__ . '/cache/', 'compiledSeparator' => '_')); $compiler = $volt->getCompiler(); // format number $compiler->addFilter('number', function ($resolvedArgs) { return 'Helpers::number(' . $resolvedArgs . ');'; }); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }; /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { $config = $config->database->toArray(); $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter']; unset($config['adapter']); return new $dbAdapter($config); }; /** * Logger service */ $di->set('logger', function ($filename = null, $format = null) use($config) { $format = $format ?: $config->get('logger')->format; $filename = trim($filename ?: $config->get('logger')->filename, '\\/'); $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR; $formatter = new FormatterLine($format, $config->get('logger')->date); $logger = new FileLogger($path . $filename); $logger->setFormatter($formatter); $logger->setLogLevel($config->get('logger')->logLevel); return $logger; }); $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri("/backend/"); return $url; }); }
/** * Initializes Volt engine */ public function register() { $di = $this->getDi(); $eventsManager = $this->getEventsManager(); $config = $this->_config; $di->set('viewEngine', function ($view, $di) use($config) { $volt = new ViewEngine($view, $di); $volt->setOptions(["compiledPath" => $config->application->view->compiledPath, "compiledExtension" => $config->application->view->compiledExtension, 'compiledSeparator' => $config->application->view->compiledSeparator, 'compileAlways' => $config->application->view->compileAlways]); $compiler = $volt->getCompiler(); $compiler->addFilter('dump', function ($resolvedArgs) { return 'var_dump(' . $resolvedArgs . ')'; }); return $volt; }); }
/** * @param $container */ public function boot(Container $container) { $container->setShared('view', function () { $view = new PhalconView(); $view->setEventsManager($this->getShared('eventsManager')); $view->setViewsDir($this->path('views')); $view->registerEngines(['.volt' => 'volt', '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']); return $view; }); $container->setShared('volt', function () { $volt = new Volt($this->get('view')); $volt->setOptions(['compiledPath' => $this->tmpPath() . '/cache/volt/', 'compiledSeparator' => '_', 'compileAlways' => true]); $volt->getCompiler()->addExtension(new \Pails\Extensions\Volt()); return $volt; }); }
/** * Registers an autoloader related to the module * * @param \Phalcon\DiInterface $dependencyInjector */ public function registerServices(\Phalcon\DiInterface $dependencyInjector) { $config = $this->config; /** * Setting up the view component */ $dependencyInjector['view'] = function () use($config) { $view = new View(); $viewDir = $this::DIR . '/views/'; if ($config->offsetExists('application') && $config->application->offsetExists('viewsDir') && $config->application->offsetExists('viewsDir')) { $viewDir = $config->application->viewsDir; } $view->setViewsDir($viewDir); $cacheDir = $this::DIR . '/cache/'; if ($config->offsetExists('application') && $config->application->offsetExists('cacheDir') && $config->application->offsetExists('cacheDir')) { $cacheDir = $config->application->cacheDir; } $view->registerEngines(array('.volt' => function ($view, $di) use($config, $cacheDir) { $volt = new VoltEngine($view, $di); $volt->setOptions(['compiledPath' => $cacheDir, 'compiledExtension' => ".compiled", 'compiledSeparator' => '_', 'compileAlways' => APP_ENV == 'product' ? false : true]); $compiler = $volt->getCompiler(); $compiler->addExtension(new \PhalconPlus\Volt\Extension\PhpFunction()); $funcList = $this->getVoltCompileFunction($di); foreach ($funcList as $k => $v) { $compiler->addFunction($k, $v); } $filterList = $this->getVoltCompileFilter($di); foreach ($filterList as $k => $v) { $compiler->addFilter($k, $v); } return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }; if ($config->offsetExists('application') && $config->application->offsetExists('baseUri')) { $dependencyInjector['url'] = function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }; } $dependencyInjector['moduleConfig'] = function () use($config) { return $config; }; }
/** * @param \Phalcon\DiInterface $di * @return mixed */ public function initialize(\Phalcon\DiInterface $di) { /** @var \Phalcon\Config $config */ $config = $di->get('config'); $viewConfig = isset($config->application->view) ? $config->application->view->toArray() : []; if ($di->has('view')) { /** @var \Phalcon\Mvc\View $view */ $view = $di->get('view'); $viewEngines = $view->getRegisteredEngines(); if (!$viewEngines) { $viewEngines = []; } $viewEngines['.volt'] = function ($this, $di) use($viewConfig) { $volt = new VoltEngine($this, $di); $volt->setOptions($viewConfig); $volt->getCompiler()->addFilter('toString', (new ToStringFilter())->getFilter()); return $volt; }; $view->registerEngines($viewEngines); } }
public function register() { $view = new PhalconView(); $view->setViewsDir(config()->path->views); $view->registerEngines(['.volt' => function ($view, $di) { $volt = new PhalconVoltEngine($view, $di); $volt->setOptions(['compiledPath' => config()->path->storage_views, 'compiledSeparator' => '_']); $compiler = $volt->getCompiler(); # others $compiler->addFunction('di', 'di'); $compiler->addFunction('env', 'env'); $compiler->addFunction('echo_pre', 'echo_pre'); $compiler->addFunction('csrf_field', 'csrf_field'); $compiler->addFunction('dd', 'dd'); $compiler->addFunction('config', 'config'); # facade $compiler->addFunction('security', 'security'); $compiler->addFunction('tag', 'tag'); $compiler->addFunction('route', 'route'); $compiler->addFunction('response', 'response'); $compiler->addFunction('view', 'view'); $compiler->addFunction('config', 'config'); $compiler->addFunction('url', 'url'); $compiler->addFunction('request', 'request'); # paths $compiler->addFunction('base_uri', 'base_uri'); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.blade.php' => 'Bootstrap\\Adapters\\Blade\\BladeAdapter']); # ---- instatiate a new event manager $event_manager = new EventsManager(); # ---- after rendering the view # by default, we should destroy the flash $event_manager->attach("view:afterRender", function ($event, $dispatcher, $exception) { # - this should destroy the flash $flash = $dispatcher->getDI()->get('flash'); $flash->destroy(); }); $view->setEventsManager($event_manager); return $view; }
/** * Registers the module-only services * * @param Phalcon\DI $di */ public function registerServices(\Phalcon\DiInterface $di = null) { /** * Read configuration */ $config = (include __DIR__ . "/config/config.php"); /** * Setting up the view component */ $di['view'] = function () use($config) { $view = new View(); $view->setViewsDir(__DIR__ . '/views/'); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_')); $compiler = $volt->getCompiler(); //Set Function PHP $compiler->addFunction('md5', 'md5'); $compiler->addFunction('base64_encode', 'base64_encode'); $compiler->addFunction('current', 'current'); $compiler->addFunction('count', 'count'); $compiler->addFunction('unserialize', 'unserialize'); $compiler->addFunction('print_r', 'print_r'); $compiler->addFunction('var_dump', 'var_dump'); $compiler->addFunction('number_format', 'number_format'); $compiler->addFunction('json_decode', 'json_decode'); $compiler->addFunction('in_array', 'in_array'); $compiler->addFunction('get_object_vars', 'get_object_vars'); $compiler->addFunction('strpos', 'strpos'); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); 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, "charset" => $config->database->charset)); }; }
/** * 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' => FA_INCLUDE_BASE . '/', 'views_dir' => 'modules/frontend/views/scripts/', 'partials_dir' => '', 'layouts_dir' => '../../../../templates/', 'layout' => 'main'); $options = array_merge($defaults, (array) $options); // Temporary fix to force "views_dir" to be the full path, because "base_dir" is not used in some Phalcon calculations. $options['views_dir'] = $options['base_dir'] . $options['views_dir']; $options['base_dir'] = ''; $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 Volt($view, $di); $volt->setOptions(array('compileAlways' => FA_APPLICATION_ENV == 'development', 'compiledPath' => function ($templatePath) { // Clean up the template path and remove non-application folders from path. $templatePath = realpath($templatePath); $templatePath = ltrim(str_replace(FA_INCLUDE_BASE, '', $templatePath), '/'); $find_replace = array('/views/scripts/' => '_', '../' => '', '/' => '_', '.volt' => ''); $templatePath = str_replace(array_keys($find_replace), array_values($find_replace), $templatePath); return FA_INCLUDE_CACHE . '/volt_' . $templatePath . '.compiled.php'; })); $compiler = $volt->getCompiler(); $compiler->addExtension(new \FA\Phalcon\Service\ViewHelper()); return $volt; })); return $view; }
if (!$config->application->debug) { $url->setBaseUri($config->application->production->baseUri); $url->setStaticBaseUri($config->application->production->staticBaseUri); } else { $url->setBaseUri($config->application->development->baseUri); $url->setStaticBaseUri($config->application->development->staticBaseUri); } return $url; }, true); /** * Setting up volt */ $di->set('volt', function ($view, $di) use($config) { $volt = new Volt($view, $di); $volt->setOptions(["compiledPath" => APP_PATH . "/app/cache/volt/", "compiledSeparator" => "_", "compileAlways" => $config->application->debug]); $volt->getCompiler()->addFunction('number_format', function ($resolvedArgs) { return 'number_format(' . $resolvedArgs . ')'; }); return $volt; }, true); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines([".volt" => 'volt']); return $view; }, true); /** * Database connection is created based in the parameters defined in the configuration file
$dispatcher = new Dispatcher(); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->setRenderLevel(View::LEVEL_ACTION_VIEW); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_', 'compileAlways' => true)); //add filter functions $compiler = $volt->getCompiler(); $compiler->addFilter('uniform_time', function ($resolvedArgs, $exprAgs) { return "date('Y-m-d H:i:s', strtotime(" . $resolvedArgs . "))"; }); $compiler->addFilter('number_format', function ($resolveArgs, $exprAgs) { return 'number_format(' . $resolveArgs . ')'; }); $compiler->addFilter('urlencode', function ($resolveArgs, $exprAgs) { return 'urlencode(' . $resolveArgs . ')'; }); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true); /** * Database connection is created based in the parameters defined in the configuration file
/** * Initializes the view and Volt * * @param array $options */ protected function initView($options = array()) { $config = $this->di['config']; $di = $this->di; /** * Setup the view service */ $this->di['view'] = function () use($config, $di) { $view = new PhView(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new PhVolt($view, $di); $voltOptions = array('compiledPath' => $config->application->voltDir, 'compiledSeparator' => '_'); if ('1' == $config->application->debug) { $voltOptions['compileAlways'] = true; } $volt->setOptions($voltOptions); $volt->getCompiler()->addFunction('tr', function ($key) { return "Bootstrap::translate({$key})"; }); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }; }
$di->setShared('url', function () use($config) { $url = new UrlProvider(); $url->setBaseUri($config->get('application')->baseUri); return $url; }); /** * Setting the View and View Engines */ $di->setShared('view', function () use($config, $di, $eventsManager) { $view = new View(); $view->registerEngines(['.volt' => function ($view, $di) use($config) { $volt = new Volt($view, $di); $path = APPLICATION_ENV == APP_TEST ? DOCROOT . 'tests/_cache/' : DOCROOT . $config->get('volt')->cacheDir; $options = ['compiledPath' => $path, 'compiledExtension' => $config->get('volt')->compiledExt, 'compiledSeparator' => $config->get('volt')->separator, 'compileAlways' => APPLICATION_ENV !== APP_PRODUCTION]; $volt->setOptions($options); $volt->getCompiler()->addFunction('strtotime', 'strtotime')->addFunction('sprintf', 'sprintf')->addFunction('str_replace', 'str_replace')->addFunction('is_a', 'is_a'); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']); $view->setVar('version', Version::get())->setViewsDir(DOCROOT . $config->get('application')->viewsDir); $eventsManager->attach('view', function ($event, $view) use($di, $config) { /** * @var \Phalcon\Events\Event $event * @var \Phalcon\Mvc\View $view */ if ($event->getType() == 'notFoundView') { $message = sprintf('View not found - %s', $view->getActiveRenderPath()); throw new Exception($message); } }); $view->setEventsManager($eventsManager); return $view;
/** * Init view (Phalcon Volt Template) * * @return View */ private function _initView() { $view = new View(); $view->setDI(Di::getDefault()); $view->registerEngines(['.volt' => function ($view, $di) { $volt = new VoltEngine($view, $di); $volt->setOptions(['compiledPath' => function ($templatePath) { $templatePath = strstr($templatePath, '/app'); $dirName = dirname($templatePath); if (!is_dir(ROOT_PATH . '/cache/volt' . $dirName)) { mkdir(ROOT_PATH . '/cache/volt' . $dirName, 0755, true); } return ROOT_PATH . '/cache/volt' . $dirName . '/' . basename($templatePath, '.volt') . '.php'; }, 'compiledSeparator' => '_', 'compileAlways' => true, 'stat' => false]); $compiler = $volt->getCompiler(); $compiler->addFunction('__', '__'); return $volt; }]); return $view; }
*/ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); /** * Setting up the view component */ $di->setShared('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_')); $volt->getCompiler()->addFilter('t', function ($resolvedArgs, $exprArgs) use($di) { return '$this->getDI()->get("translate")->_(' . $resolvedArgs . ')'; }); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { return new DbAdapter($config->database->toArray()); }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */
protected function _registerServices() { $config = (include $this->appConfigDirectory . "config.php"); if (isset($config['mode'])) { self::$mode = $config->mode; } $this->di['config'] = $config; $this->di['dispatcher'] = function () { $dispatcher = new Dispatcher(); // $this->eventManager->attach('dispatch', new HttpResponsePlugin()); // // $dispatcher->setEventsManager($this->eventManager); //注册默认controller目录 $dispatcher->setDefaultNamespace('myweb\\twoweb\\Controllers\\home'); return $dispatcher; }; /** * 数据库设定, 自动读取配置中的所有数据库 */ call_user_func(function () { $logger = $this->getLogger('mysql'); $configs = (include $this->globalConfigDirectory . "mysql.php"); $configs = $configs[self::$mode]; foreach ($configs as $name => $_config) { $this->di['db.' . "{$name}"] = function () use($logger, $name, $_config) { $this->eventManager->attach('db', function ($event, $connection) use($logger, $name) { if ($event->getType() == 'beforeQuery') { // $logger->log("[$name]: " .$connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); $mysql = new MysqlDB($_config); $mysql->setEventsManager($this->eventManager); return $mysql; }; } }); /** * mongodb */ call_user_func(function () { $configs = (include $this->globalConfigDirectory . "mongo.php"); $configs = $configs[self::$mode]; $logger = $this->getLogger('mongo'); foreach ($configs as $name => $_config) { $this->di['mongo' . ".{$name}"] = function () use($name, $_config) { $auth = ""; if (!empty($_config['username']) && !empty($_config['password'])) { $auth = $_config['username'] . ":" . $_config['password'] . "@"; } $connection = new MongoDB("mongodb://{$auth}{$_config['host']}:{$_config['port']}/{$_config['dbname']}"); return $connection->selectDB($_config['dbname']); }; } }); // collection log $this->di['collectionManager'] = function () { $modelsManager = new CollectionManager(); $modelsManager->setEventsManager($this->eventManager); return $modelsManager; }; $this->di->set('voltService', function ($view, $di) { $volt = new Volt($view, $di); $volt->setOptions(array('compiledPath' => APP_CACHE_PATH . "caches_template" . DIRECTORY_SEPARATOR, 'compiledExtension' => '.compiled', 'compileAlways' => false)); $compiler = $volt->getCompiler(); $compiler->addFilter('array_slice', 'array_slice'); return $volt; }); $this->di->set('view', function () { $view = new View(); $view->setViewsDir(APP_PATH . "views"); $view->registerEngines(array(".html" => 'voltService')); return $view; }, true); $this->di['router'] = function () { $router = (include $this->appConfigDirectory . "router.php"); return $router; }; $this->di['logger'] = function () { $logger = $this->getLogger("debug"); return $logger; }; $this->di['mongolog'] = function () { $logger = $this->getLogger("mongo"); return $logger; }; /** * redis 设定 */ call_user_func(function () { $configs = (include $this->globalConfigDirectory . "redis.php"); $configs = $configs[self::$mode]; foreach ($configs as $name => $_config) { $this->di->set('redis.' . $name, function () use($_config) { return $this->connectRedis($_config); }); } }); /** * 缓存设定 */ $this->di['cache'] = function () { //1 days $frontCache = new FrontCache(array('lifetime' => 86400)); return new FileCache($frontCache, array('cacheDir' => APP_CACHE_PATH . "caches_data" . DIRECTORY_SEPARATOR)); }; /** * Model Cache */ $this->di['modelsCache'] = function () { return $this->di['cache']; }; $this->di['modelsMetadata'] = function () { //1 days $metaDataCache = new FileMetaData(array('lifetime' => 86400, 'metaDataDir' => APP_CACHE_PATH . "caches_metadata" . DIRECTORY_SEPARATOR)); return $metaDataCache; }; }
/** * * @param type $options */ protected function initView($options = []) { $config = $this->_di->get('config'); $di = $this->_di; if (!file_exists($config->volt->path)) { mkdir($config->volt->path, 0777, true); } $this->_di->setShared('volt', function ($view, $di) use($config) { $volt = new Volt($view, $di); $volt->setOptions(['compiledPath' => $config->volt->path, 'compiledExtension' => $config->volt->extension, 'compiledSeparator' => $config->volt->separator, 'compileAlways' => (bool) $config->volt->compileAlways, 'stat' => (bool) $config->volt->stat]); $compiler = $volt->getCompiler(); $compiler->addFunction('is_a', 'is_a'); return $volt; }); $this->_di->setShared('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->setMainView('index'); $view->setLayoutsDir('layouts/'); $view->setPartialsDir('partials/'); $view->registerEngines(['.volt' => 'volt', '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']); return $view; }); }
/** * Initialize the View. * * Setting up the view component. * * * @param DiInterface $di Dependency Injector * @param Config $config App config * @param EventsManager $em Events Manager * * @return Loader */ protected function initView(DiInterface $di, Config $config, EventsManager $em) { $di->set('view', function () use($di, $config, $em) { $view = new View(); $view->registerEngines(['.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $voltConfig = $config->get('volt')->toArray(); $options = ['compiledPath' => $voltConfig['cacheDir'], 'compiledExtension' => $voltConfig['compiledExt'], 'compiledSeparator' => $voltConfig['separator'], 'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile']]; $volt->setOptions($options); $compiler = $volt->getCompiler(); $compiler->addFunction('number_format', function ($resolvedArgs) { return 'number_format(' . $resolvedArgs . ')'; }); $compiler->addFunction('chr', function ($resolvedArgs) { return 'chr(' . $resolvedArgs . ')'; }); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']); $view->setViewsDir($config->get('application')->viewsDir); $em->attach('view', function ($event, $view) use($di, $config) { /** * @var LoggerInterface $logger * @var View $view * @var Event $event * @var DiInterface $di */ $logger = $di->get('logger'); $logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath())); if ('notFoundView' == $event->getType()) { $message = sprintf('View not found: %s', $view->getActiveRenderPath()); $logger->error($message); throw new ViewException($message); } }); $view->setEventsManager($em); return $view; }); }
$di->set('viewSimple', function () use($config) { $view = new \Phalcon\Mvc\View\Simple(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(['.volt' => function ($view, $di) { return new \Phalcon\Mvc\View\Engine\Volt($view, $di); }]); return $view; }); $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_', 'compileAlways' => true)); //agregamos toda la sfuncoines de php $volt->getCompiler()->addExtension(new \App\Libraries\PhpFunctionExtension()); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.php' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true); /** * View cache */ $di->set('viewCache', function () use($config) { if (!$config->application->production) { $frontCache = new \Phalcon\Cache\Frontend\None(); } else { //Cache data for one day by default $frontCache = new \Phalcon\Cache\Frontend\Output(array("lifetime" => 172800)); } return new \Phalcon\Cache\Backend\File($frontCache, array("cacheDir" => APP_PATH . "/app/cache/views/", "prefix" => "site-cache-"));
use Phalcon\Cache\Frontend\Output as FrontendOutput; $di->set('url', function () use($config) { $url = new UrlResolver(); if (!$config->application->debug) { $url->setBaseUri($config->application->production->baseUri); $url->setStaticBaseUri($config->application->production->staticBaseUri); } else { $url->setBaseUri($config->application->development->baseUri); $url->setStaticBaseUri($config->application->development->staticBaseUri); } return $url; }, true); $di->set('volt', function ($view, $di) use($config) { $volt = new Volt($view, $di); $volt->setOptions(["compiledPath" => APP_PATH . "/app/cache/volt/", "compiledSeparator" => "_", "compileAlways" => $config->application->debug]); $volt->getCompiler()->addFunction('glyphicon', function ($resolvedArgs, $exprArgs) use($volt) { return '"<span class=\\"glyphicon glyphicon-' . $exprArgs[0]["expr"]["value"] . '\\" aria-hidden=\'true\'></span> "'; }); return $volt; }, true); $di->set('markdown', function ($view, $di) use($config) { $markdown = new \CloudOJ\MarkdownAdapter($view, $di); $markdown->setOptions(["compiledPath" => APP_PATH . "/app/cache/markdown/", "compiledSeparator" => "_", "compileAlways" => $config->application->debug]); return $markdown; }, true); $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines([".volt" => 'volt', ".md" => 'markdown']); return $view; }, true);
/** * Initializes the view and Volt * * @param array $options */ public function initView($options = []) { $di = $this->di; $config = $di['config']; $this->di['volt'] = function ($view, $di) use($config) { $volt = new PhVolt($view, $di); $volt->setOptions(['compiledPath' => $config->app_volt->path, 'compiledExtension' => $config->app_volt->extension, 'compiledSeparator' => $config->app_volt->separator, 'compileAlways' => true]); $compiler = $volt->getCompiler(); $compiler->addFilter('floor', 'floor'); $compiler->addFunction('range', 'range'); return $volt; }; /** * Setup the view service */ $this->di['view'] = function () { $view = new PhView(); $view->registerEngines(['.volt' => 'volt']); return $view; }; }
* Date: 07-08-2015 * Time: 16:10 PM * * @var \Phalcon\Config $config */ use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Volt as VoltEngine; $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->setVars($config->view->vars->toArray()); $view->registerEngines(['.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions($config->volt->options->toArray()); $functions = $config->volt->functions->toArray(); foreach ($functions as $name => $function) { $volt->getCompiler()->addFunction($name, function ($params) use($function) { if (is_array($function)) { $funcArray = $function; $function = $funcArray['function']; if (isset($funcArray['params']) && !empty($funcArray['params'])) { if (!is_array($params)) { $params = (array) $params; } $params = array_merge($params, $funcArray['params']); $params = serialize(array_filter($params)); return "{$function}(unserialize('{$params}'))"; } } if (strpos($function, '{params}') !== false) { return str_replace('{params}', $params, $function); } else {