Example #1
0
function setDi()
{
    $di = new FactoryDefault();
    $di['router'] = function () use($di) {
        $router = new Router();
        $router->setDefaultModule('admin');
        return $router;
    };
    $di['url'] = function () {
        $url = new UrlResolver();
        $url->setBaseUri('/');
        return $url;
    };
    $di['session'] = function () {
        $session = new SessionAdapter();
        $session->start();
        return $session;
    };
    $loader = new Loader();
    $loader->registerNamespaces(array('Mall\\Mdu' => __DIR__ . '/../apps/mdu'));
    $sysConfig = (include __DIR__ . '/../config/sysconfig.php');
    $di['sysconfig'] = function () use($sysConfig) {
        return $sysConfig;
    };
    $loader->register();
    return $di;
}
 /**
  * @param DI $di
  */
 public function registerServices($di)
 {
     //Registering a dispatcher
     $di->setShared('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace("Admin");
         $eventsManager = $di->getShared('eventsManager');
         $eventsManager->attach('dispatch', new AdminSecurity($di));
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     $auto_admin = new \AutoAdmin\Module();
     $auto_admin->registerServices($di);
     $di->setShared('admin_views_dir', function () {
         return ADMINROOT . '/views/';
     });
     $di->setShared('session', function () {
         $session = new Session();
         $session->start();
         return $session;
     });
     $di->setShared('config', function () use($di) {
         $configFront = (require COREROOT . '/app/config/config.php');
         $configBack = (require ADMINROOT . '/config/config.php');
         $configFront->merge($configBack);
         return $configFront;
     });
 }
Example #3
0
 /**
  * Initializes the session
  *
  * @param array $options
  */
 protected function initSession($options = array())
 {
     $this->di['session'] = function () {
         $session = new PhSession();
         $session->start();
         return $session;
     };
 }
Example #4
0
 /**
  * Registers the session component in the DI container.
  * 
  * @return void
  */
 public function register()
 {
     $this->di->setShared('session', function () {
         $session = new SessionAdapter();
         if (!$session->isStarted()) {
             $session->start();
         }
         return $session;
     });
 }
Example #5
0
 /**
  * Register services used by the backend application
  *
  * @param $di
  */
 public function registerServices($di)
 {
     $config = $this->config();
     /**
      * register the dispatcher
      */
     $di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         /*$eventManager = new Manager();
                     $eventManager->attach('dispatch', new \Acl('backend'));
         
                     $dispatcher->setEventsManager($eventManager);*/
         $dispatcher->setDefaultNamespace('app\\backend\\controllers');
         return $dispatcher;
     });
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($config) {
         $url = new UrlResolver();
         $url->setBaseUri($config->application->baseUri);
         return $url;
     }, true);
     $di->setShared('view', function () use($config) {
         $view = new View();
         $view->setViewsDir($config->application->viewsDir);
         $view->registerEngines(['.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(['compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_']);
             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 MysqlAdapter($config->database->toArray());
     });
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $di->set('modelsMetadata', function () {
         return new MetaDataAdapter();
     });
     /**
      * Start the session the first time some component request the session service
      */
     $di->setShared('session', function () {
         $session = new SessionAdapter();
         $session->start();
         return $session;
     });
 }
 public function onBoot()
 {
     // TODO: Implement onBoot() method.
     $this->getDI()->setShared('session', function () {
         $session = new Session();
         if (!$session->isStarted()) {
             $session->start();
         }
         return $session;
     });
 }
Example #7
0
 /**
  * @inheritdoc
  */
 public function connect(array $config)
 {
     $session = new SessionAdapter();
     $id = di('crypt')->encrypt($config['app']['key']);
     $name = $config['session']['cookie'];
     //$session->setId($id);
     session_name($name);
     $session->setOptions(['uniqueId' => $id]);
     if (!$session->isStarted()) {
         $session->start();
     }
     return $session;
 }
Example #8
0
 public function __construct($options = null)
 {
     parent::__construct($options);
     $sessionPath = $options['save_path'];
     is_dir($sessionPath) or mkdir($sessionPath, 0755, true);
     session_save_path($sessionPath);
 }
 /**
  * Destroys current session and removes session cookie
  * @return bool
  */
 public function destroy()
 {
     // Remove session cookie
     $options = $this->getCookieOptions();
     if (!setcookie($options['name'], '', -1)) {
         return false;
     }
     // Clean session data
     return parent::destroy();
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function __construct($options)
 {
     parent::__construct($options);
     if (!is_cli()) {
         if (isset($options['session_storage']) === false) {
             $options['session_storage'] = url_trimmer(config()->path->storage . '/session');
         }
         session_save_path($options['session_storage']);
         session_set_cookie_params($options['lifetime'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
     }
 }
Example #11
0
 /**
  *
  * @param \Phalcon\DI $di
  */
 public function registerServices($di)
 {
     Admin::instance();
     require __DIR__ . '/../../../../phad/phad.php';
     $di['phadConfig'] = function () {
         $config = (require __DIR__ . '/../../../../phad-config.php');
         return new Config($config);
     };
     $di['view'] = function () {
         $view = new ViewEngine();
         $view->setViewsDir(__DIR__ . '/Views/');
         $view->setLayoutsDir('Layouts/');
         $view->setPartialsDir('Partials/');
         return $view;
     };
     $di['viewSimple'] = function () {
         $view = new Simple();
         $view->setViewsDir(__DIR__ . '/Views/');
         return $view;
     };
     $di['flashSession'] = function () {
         $flashClasses = ['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning'];
         return new FlashSession($flashClasses);
     };
     $di['session'] = function () {
         $session = new Session();
         $session->start();
         return $session;
     };
     $di['phadAuth'] = function () {
         return new Auth();
     };
     $di['assets'] = function () use($di) {
         $options = ['sourceBasePath' => __DIR__ . '/Assets/', 'targetBasePath' => __DIR__ . '/../../../../public/backend-assets/'];
         $assets = new AssetsManager($options);
         $assets->collection('backend_css')->setTargetPath('final.css')->setTargetUri('backend-assets/final.css')->addCss('bootstrap/css/bootstrap.min.css')->addCss('css/styles.css')->join(true)->addFilter(new AssetsNullFilter());
         $assets->collection('backend_js')->setTargetPath('final.js')->setTargetUri('backend-assets/final.js')->addJs('bootstrap/js/bootstrap.min.js')->addJs('js/custom.js')->join(true)->addFilter(new AssetsNullFilter());
         return $assets;
     };
 }
Example #12
0
 /**
  * Phalcon\Session\Adapter\Files constructor
  *
  * @param array $options
  */
 public function __construct($options = null)
 {
     if (isset($options['name'])) {
         ini_set('session.name', $options['name']);
     }
     if (isset($options['lifetime'])) {
         ini_set('session.gc_maxlifetime', $options['lifetime']);
     }
     if (isset($options['cookie_lifetime'])) {
         ini_set('session.cookie_lifetime', $options['cookie_lifetime']);
     }
     parent::__construct($options);
 }
    $adapter = $dbConfig['adapter'];
    unset($dbConfig['adapter']);
    $class = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
    return new $class($dbConfig);
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new MetaDataAdapter();
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();
    (new TranslateEngine())->initialize($session);
    return $session;
});
$di->set('dispatcher', function () {
    // Create an event manager
    $eventsManager = new EventsManager();
    // Attach a listener for type "dispatch"
    $eventsManager->attach("dispatch", function ($event, $dispatcher) {
        // ...
    });
    $dispatcher = new MvcDispatcher();
    // Bind the eventsManager to the view component
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
Example #14
0
 /**
  * Initializes the session
  *
  * @param array $options
  */
 protected function initSession($options = array())
 {
     $config = $this->di['config'];
     $this->di['session'] = function () use($config) {
         $session = new PhSession(array('uniqueId' => $config->application->appName));
         $session->start();
         return $session;
     };
 }
Example #15
0
 /**
  * 默认服务依赖注入
  *
  */
 protected function commonServices()
 {
     $mode = $this->mode;
     $di = $this->mode === 'CLI' ? new Cli() : new FactoryDefault();
     // 日志
     $di->set('logger', function () {
         $config = load('logger');
         $adapter = $config['adapter'];
         $filename = $config[$adapter]['filename'];
         $filedir = dirname($filename);
         if (empty($config)) {
             throw new \Exception('logger config Require failed');
         }
         if (!is_dir($filedir)) {
             mkdir($filedir, 0755, true);
         }
         $logger = new File($filename);
         $formatter = new Line(null, 'Y-m-d H:i:s');
         $loglevel = config('app.loglevel');
         $logger->setFormatter($formatter);
         $logger->setLogLevel($loglevel ? $loglevel : \Phalcon\Logger::ERROR);
         return $logger;
     }, true);
     $this->application->setDI($di);
     // 命名空间
     $di->set('dispatcher', function () use($mode) {
         $dispatcher = new Dispatcher();
         $dispatcher = $mode === 'CLI' ? new \Phalcon\CLI\Dispatcher() : new Dispatcher();
         $bootstrap = load('bootstrap');
         $default = $bootstrap['dispatcher'];
         $dispatcher->setDefaultNamespace($mode === 'CLI' ? $default['cli'] : $default['default']);
         return $dispatcher;
     }, true);
     // 路由
     if ($load = load('router', null, true)) {
         if ($load instanceof Router) {
             $di->set('router', $load);
         }
     }
     // 视图
     $di->set('view', function () {
         $view = new View();
         $view->setViewsDir(APP_VIEW);
         return $view;
     }, true);
     // 加解密
     if ($config = config('crypt')) {
         $di->set('crypt', function () use($config) {
             $crypt = new Crypt();
             $crypt->setKey($config['authkey']);
             return $crypt;
         }, true);
     }
     // 默认缓存
     if ($config = config('cache')) {
         $di->set('cache', function () use($config) {
             $cache = null;
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             $frontend = new Data(array('lifetime' => $config['lifetime']));
             switch ($adapter) {
                 case 'memcache':
                     $cache = new Memcache($frontend, $options);
                     break;
                 case 'redis':
                     if (empty($options['auth'])) {
                         unset($options['auth']);
                     }
                     $cache = new \Phalcon\Extend\Cache\Backend\Redis($frontend, $options);
                     break;
             }
             return $cache;
         }, true);
     }
     // Cookies
     if ($config = config('cookies')) {
         $di->set('cookies', function () use($config) {
             $cookies = new \Phalcon\Extend\Http\Response\Cookies($config);
             if (!config('crypt.authkey')) {
                 $cookies->useEncryption(false);
             }
             return $cookies;
         }, true);
     }
     // Session
     if ($config = config('session')) {
         $di->set('session', function () use($config) {
             if (!empty($config['options'])) {
                 foreach ($config['options'] as $name => $value) {
                     ini_set("session.{$name}", $value);
                 }
             }
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             switch ($adapter) {
                 case 'memcache':
                     $session = new SessionMemcache($options);
                     break;
                 case 'redis':
                     $session = new \Phalcon\Extend\Session\Adapter\Redis($options);
                     break;
                 default:
                     $session = new SessionFiles();
                     break;
             }
             $session->start();
             return $session;
         }, true);
     }
     // Db
     if ($config = config('db')) {
         $di->set('db', function () use($config) {
             $mysql = new Mysql($config);
             if (debugMode()) {
                 $eventsManager = new Manager();
                 $logger = new File(APP_LOG . DS . 'Mysql' . LOGEXT);
                 $formatter = new Line(null, 'Y-m-d H:i:s');
                 $logger->setFormatter($formatter);
                 $eventsManager->attach('db', function ($event, $mysql) use($logger) {
                     if ($event->getType() == 'beforeQuery') {
                         $logger->log($mysql->getSQLStatement(), Logger::INFO);
                     }
                     if ($event->getType() == 'afterQuery') {
                     }
                 });
                 $mysql->setEventsManager($eventsManager);
             }
             return $mysql;
         }, true);
     }
     // DB 元信息
     if ($config = config('metadata')) {
         $di->set('modelsMetadata', function () use($config) {
             $modelsMetadata = null;
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             switch ($adapter) {
                 case 'memcache':
                     $modelsMetadata = new MetaDataMemcache($options);
                     break;
                 case 'redis':
                     if (empty($options['auth'])) {
                         unset($options['auth']);
                     }
                     $modelsMetadata = new MetaDataRedis($options);
                     break;
             }
             return $modelsMetadata;
         }, true);
     }
     $this->application->setDI($di);
 }
Example #16
0
 /**
  * Init session.
  *
  * @param DI     $di     Dependency Injection.
  * @param Config $config Config object.
  *
  * @return SessionAdapter
  */
 protected function _initSession($di, $config)
 {
     $session = new PhSessionFiles();
     $session->start();
     $di->setShared('session', $session);
     return $session;
 }
Example #17
0
 /**
  * Register services used by the frontend application
  *
  * @param $di
  */
 public function registerServices(FactoryDefault $di)
 {
     $config = $this->config();
     /**
      * register the dispatcher
      */
     $di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         /*$eventManager = new Manager();
                     $eventManager->attach('dispatch', new \Acl('frontend'));
         
                     $dispatcher->setEventsManager($eventManager);*/
         $dispatcher->setDefaultNamespace('app\\frontend\\controllers');
         return $dispatcher;
     });
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($config) {
         $url = new UrlResolver();
         $url->setBaseUri($config->application->baseUri);
         return $url;
     }, true);
     $di->setShared('view', function () use($config) {
         $view = new View();
         $view->setViewsDir($config->application->viewsDir);
         $view->registerEngines(['.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(['compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_']);
             /**
              * add functions to compiler
              */
             VoltHelper::registerViewFunctions($volt, VoltHelper::getUtil(['ng']));
             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 MysqlAdapter($config->database->toArray());
     });
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $di->set('modelsMetadata', function () {
         return new MetaDataAdapter();
     });
     /**
      * Start the session the first time some component request the session service
      */
     $di->setShared('session', function () {
         $session = new SessionAdapter();
         $session->start();
         return $session;
     });
     /**
      * Set the auth component
      */
     $di->set('auth', function () {
         $auth = new Auth();
         $auth->setSuccessUrl('/index/index');
         $auth->setFailUrl('session/login');
         return $auth;
     });
     //        /**
     //         * List of assets that need to be loaded
     //         */
     //        $di->setShared('asset_config', function () {
     //            return require_once(APP_PATH . '/frontend/config/assets.php');
     //        });
 }
Example #18
0
 public function register()
 {
     $session = new SessionAdapter();
     $session->start();
     return $session;
 }
Example #19
0
 /**
  *
  * @param type $options
  */
 protected function initSession($options = [])
 {
     $this->_di->setShared('session', function () {
         $session = new Session(['uniqueId' => 'api_phalcon-']);
         if (!$session->isStarted()) {
             $session->start();
         }
         return $session;
     });
 }
Example #20
0
 /**
  * @param RegisterService $registerService
  */
 public function register(RegisterService $registerService)
 {
     $session = new SessionAdapter();
     $session->start();
     $registerService->getDependencyInjection()->set('session', $session);
 }
Example #21
0
 private function setSession()
 {
     $session = new SessionAdapter();
     $session->start();
     return $session;
 }
 /**
  * Initializes the session
  *
  * @param array $options
  */
 protected function initSession($options = array())
 {
     $this->_di->set('session', function () {
         $session = new PhSession();
         if (!$session->isStarted()) {
             $session->start();
         }
         return $session;
     });
 }
Example #23
0
 /**
  * Initializes the session
  *
  * @param array $options
  */
 public function initSession($options = [])
 {
     $this->di->setShared('session', function () {
         $session = new PhSession();
         $session->start();
         return $session;
     });
 }
Example #24
0
 public static function run(DiInterface $di, array $options = [])
 {
     $memoryUsage = memory_get_usage();
     $currentTime = microtime(true);
     /**
      * The app path
      */
     if (!defined('K_PATH')) {
         define('K_PATH', dirname(dirname(dirname(__FILE__))));
     }
     /**
      * We will need the Utils class
      */
     require_once K_PATH . '/library/Kitsune/Utils.php';
     /**
      * Utils class
      */
     $utils = new Utils();
     $di->set('utils', $utils, true);
     /**
      * Check if this is a CLI app or not
      */
     $cli = $utils->fetch($options, 'cli', false);
     if (!defined('K_CLI')) {
         define('K_CLI', $cli);
     }
     $tests = $utils->fetch($options, 'tests', false);
     if (!defined('K_TESTS')) {
         define('K_TESTS', $tests);
     }
     /**
      * The configuration is split into two different files. The first one
      * is the base configuration. The second one is machine/installation
      * specific.
      */
     if (!file_exists(K_PATH . '/var/config/base.php')) {
         throw new \Exception('Base configuration files are missing');
     }
     if (!file_exists(K_PATH . '/var/config/config.php')) {
         throw new \Exception('Configuration files are missing');
     }
     /**
      * Get the config files and merge them
      */
     $base = (require K_PATH . '/var/config/base.php');
     $specific = (require K_PATH . '/var/config/config.php');
     $combined = array_replace_recursive($base, $specific);
     $config = new Config($combined);
     $di->set('config', $config, true);
     $config = $di->get('config');
     /**
      * Check if we are in debug/dev mode
      */
     if (!defined('K_DEBUG')) {
         $debugMode = boolval($utils->fetch($config, 'debugMode', false));
         define('K_DEBUG', $debugMode);
     }
     /**
      * Access to the debug/dev helper functions
      */
     if (K_DEBUG) {
         require_once K_PATH . '/library/Kitsune/Debug.php';
     }
     /**
      * We're a registering a set of directories taken from the
      * configuration file
      */
     $loader = new Loader();
     $loader->registerNamespaces($config->namespaces->toArray());
     $loader->register();
     require K_PATH . '/vendor/autoload.php';
     /**
      * LOGGER
      *
      * The essential logging service
      */
     $format = '[%date%][%type%] %message%';
     $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log';
     $logger = new LoggerFile($name);
     $formatter = new LoggerFormatter($format);
     $logger->setFormatter($formatter);
     $di->set('logger', $logger, true);
     /**
      * ERROR HANDLING
      */
     ini_set('display_errors', boolval(K_DEBUG));
     error_reporting(E_ALL);
     set_error_handler(function ($exception) use($logger) {
         if ($exception instanceof \Exception) {
             $logger->error($exception->__toString());
         } else {
             $logger->error(json_encode(debug_backtrace()));
         }
     });
     set_exception_handler(function (\Exception $exception) use($logger) {
         $logger->error($exception->getMessage());
     });
     register_shutdown_function(function () use($logger, $memoryUsage, $currentTime) {
         $memoryUsed = number_format((memory_get_usage() - $memoryUsage) / 1024, 3);
         $executionTime = number_format(microtime(true) - $currentTime, 4);
         if (K_DEBUG) {
             $logger->info('Shutdown completed [Memory: ' . $memoryUsed . 'Kb] ' . '[Execution: ' . $executionTime . ']');
         }
     });
     $timezone = $config->get('app_timezone', 'US/Eastern');
     date_default_timezone_set($timezone);
     /**
      * Routes
      */
     if (!K_CLI) {
         $di->set('router', function () use($config) {
             $router = new Router(false);
             $router->removeExtraSlashes(true);
             $routes = $config->routes->toArray();
             foreach ($routes as $pattern => $options) {
                 $router->add($pattern, $options);
             }
             return $router;
         }, true);
     }
     /**
      * We register the events manager
      */
     $di->set('dispatcher', function () use($di) {
         $eventsManager = new EventsManager();
         /**
          * Handle exceptions and not-found exceptions using NotFoundPlugin
          */
         $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin());
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace('Kitsune\\Controllers');
         return $dispatcher;
     });
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($config) {
         $url = new UrlProvider();
         $url->setBaseUri($config->baseUri);
         return $url;
     });
     $di->set('view', function () use($config) {
         $view = new View();
         $view->setViewsDir(K_PATH . '/app/views/');
         $view->registerEngines([".volt" => 'volt']);
         return $view;
     });
     /**
      * Setting up volt
      */
     $di->set('volt', function ($view, $di) {
         $volt = new VoltEngine($view, $di);
         $volt->setOptions(["compiledPath" => K_PATH . '/var/cache/volt/', 'stat' => K_DEBUG, 'compileAlways' => K_DEBUG]);
         return $volt;
     }, true);
     /**
      * Start the session the first time some component request the session
      * service
      */
     $di->set('session', function () {
         $session = new SessionAdapter();
         $session->start();
         return $session;
     });
     /**
      * Cache
      */
     $frontConfig = $config->cache_data->front->toArray();
     $backConfig = $config->cache_data->back->toArray();
     $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
     $frontCache = new $class($frontConfig['params']);
     $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
     $cache = new $class($frontCache, $backConfig['params']);
     $di->set('cache', $cache, true);
     /**
      * viewCache
      */
     $di->set('viewCache', function () use($config) {
         $frontConfig = $config->cache_view->front->toArray();
         $backConfig = $config->cache_view->back->toArray();
         $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
         $frontCache = new $class($frontConfig['params']);
         $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
         $cache = new $class($frontCache, $backConfig['params']);
         return $cache;
     });
     /**
      * Markdown renderer
      */
     $di->set('markdown', function () {
         $ciconia = new Ciconia();
         $ciconia->addExtension(new FencedCodeBlockExtension());
         $ciconia->addExtension(new TaskListExtension());
         $ciconia->addExtension(new InlineStyleExtension());
         $ciconia->addExtension(new WhiteSpaceExtension());
         $ciconia->addExtension(new TableExtension());
         $ciconia->addExtension(new UrlAutoLinkExtension());
         $ciconia->addExtension(new MentionExtension());
         $extension = new IssueExtension();
         $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/issues/%s)');
         $ciconia->addExtension($extension);
         $extension = new PullRequestExtension();
         $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/pull/%s)');
         $ciconia->addExtension($extension);
         return $ciconia;
     }, true);
     /**
      * Posts Finder
      */
     $di->set('finder', function () use($utils, $cache) {
         $key = 'post.finder.cache';
         $postFinder = $utils->cacheGet($key);
         if (null === $postFinder) {
             $postFinder = new PostFinder();
             $cache->save($key, $postFinder);
         }
         return $postFinder;
     }, true);
     /**
      * For CLI I only need the dependency injector
      */
     if (K_CLI) {
         return $di;
     } else {
         $application = new Application($di);
         if (K_TESTS) {
             return $application;
         } else {
             return $application->handle()->getContent();
         }
     }
 }
Example #25
0
 public static function load(&$di, &$config)
 {
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($config) {
         $url = new UrlResolver();
         $url->setBaseUri($config->application->baseUri);
         return $url;
     }, true);
     /**
      * Setting up the view component
      */
     $di->set('view', function () use($config) {
         $view = new View();
         $view->setViewsDir($config->application->viewsDir);
         return $view;
     }, true);
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di->set('db', function () use($config) {
         $db = new DbAdapter((array) $config->database);
         $db->timeout = $config->database->timeout;
         $db->start = time();
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('db', function ($event, $db) {
             if ($event->getType() == 'beforeQuery') {
                 $idle = time() - $db->start;
                 if ($idle > $db->timeout) {
                     $db->connect();
                     $db->start = time();
                 }
             }
             return true;
         });
         return $db;
     });
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $di->set('modelsMetadata', function () {
         return new MetaDataAdapter();
     });
     /**
      * Start the session the first time some component request the session service
      */
     $di->set('session', function () {
         $session = new SessionAdapter();
         $session->start();
         return $session;
     });
     /**
      * Set encryption
      */
     $di->set('crypt', function () {
         $crypt = new Phalcon\Crypt();
         $crypt->setKey('&fhm8.2$m62$/,1@');
         return $crypt;
     }, true);
     /**
      * Set security component to validate / generate tokens
      */
     $di->set('secure', function () {
         return new SecurityComponent();
     });
 }
Example #26
0
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
$di = new FactoryDefault();
$di->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
}, true);
$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));
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
}, true);
$di->set('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));
});
$di->set('modelsMetadata', function () {
    return new MetaDataAdapter();
});
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
 /**
  * Instantiate session.
  */
 private function setSession()
 {
     $this->di->set('session', function () {
         $session = new Session();
         $session->start();
         return $session;
     });
 }