예제 #1
0
 /**
  * Registers the module-only services
  *
  * @param Phalcon\DI $di
  */
 public function registerServices($di)
 {
     /**
      * Read configuration
      */
     $config = (include __DIR__ . "/config/config.php");
     $di['view']->setViewsDir(__DIR__ . '/views/');
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di['db'] = function () use($config) {
         $connection = new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname));
         $eventsManager = new EventsManager();
         $logger = new FileLogger(__DIR__ . "/logs/db.log");
         //Listen all the database events
         $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) {
             $sqlVariables = $connection->getSQLVariables();
             if (count($sqlVariables)) {
                 $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), Logger::INFO);
             } else {
                 $logger->log($connection->getSQLStatement(), Logger::INFO);
             }
         });
         //Assign the eventsManager to the db adapter instance
         $connection->setEventsManager($eventsManager);
         return $connection;
     };
 }
예제 #2
0
 private function setDB()
 {
     $connection = new DatabaseConnection($this->database->toArray());
     $debug = $this->application->debug;
     if ($debug) {
         $eventsManager = new EventsManager();
         $logger = new FileLogger(__DIR__ . "/../Logs/db.log");
         //Listen all the database events
         $eventsManager->attach('db', function ($event, $connection) use($logger) {
             if ($event->getType() == 'beforeQuery') {
                 $variables = $connection->getSQLVariables();
                 if ($variables) {
                     $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO);
                 } else {
                     $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
                 }
             }
         });
         $connection->setEventsManager($eventsManager);
     }
     return $connection;
 }
예제 #3
0
 /**
  * Initializes the database
  *
  * @param array $options
  */
 protected function initDatabase($options = array())
 {
     $config = $this->di['config'];
     // setup database service
     $this->di['db'] = function () use($config) {
         $connection = new PhMysql(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname));
         // log sql statements
         if ('1' == $config->application->debug) {
             $eventsManager = new EventsManager();
             $logger = new PhLogFileAdapter($config->application->logDir . "/db.log");
             //Listen all the database events
             $eventsManager->attach('db', function ($event, $connection) use($logger) {
                 if ($event->getType() == 'beforeQuery') {
                     $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
                 }
             });
             // Assign the eventsManager to the db adapter instance
             $connection->setEventsManager($eventsManager);
         }
         return $connection;
     };
 }
예제 #4
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);
 }
예제 #5
0
 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;
     };
 }
예제 #6
0
 /**
  *
  * @param type $options
  */
 protected function initDatabase($options = [])
 {
     $config = $this->_di->get('config');
     $databases = $this->_di->get('databases');
     $logger = $this->_di->get('loggerDb');
     $environment = $config->application->environment != 'production' ? true : false;
     foreach ($databases->database as $key => $value) {
         $this->_di->setShared($key, function () use($value, $logger, $environment, $key) {
             if ($environment) {
                 $eventsManager = new EventsManager();
                 $dbListener = new DbListener();
                 $eventsManager->attach($key, $dbListener);
             }
             $params = ['host' => $value->host, 'username' => $value->username, 'password' => $value->password, 'dbname' => $value->dbname, 'schema' => $value->schema, 'charset' => $value->charset, 'options' => [PDO::ATTR_PERSISTENT => TRUE, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING]];
             switch ($value->adapter) {
                 case 'Oracle':
                     $conn = new Oracle($params);
                     $params['options'][PDO::ATTR_CASE] = PDO::CASE_UPPER;
                     break;
                 case 'Mysql':
                     $conn = new Mysql($params);
                     break;
             }
             if ($environment) {
                 $conn->setEventsManager($eventsManager);
             }
             return $conn;
         });
     }
     $this->_di->setShared('modelsMetadata', function () use($config) {
         if (isset($config->model->metadata->on) && $config->model->metadata->on) {
             if ($config->model->metadata->adapter == 'Files') {
                 if (!file_exists($config->model->metadata->path)) {
                     mkdir($config->model->metadata->path, 0777, true);
                 }
                 $modelsMetadata = new MetadataFiles(['metaDataDir' => $config->model->metadata->path]);
                 return $modelsMetadata;
             }
             if ($config->model->metadata->adapter == 'Apc') {
                 $modelsMetadata = new MetadataApc(array('prefix' => 'mpe-intranet-', 'lifetime' => 86400));
                 return $modelsMetadata;
             } else {
                 return new MetadataMemory();
             }
         } else {
             return new MetadataMemory();
         }
     });
     $this->_di->setShared('modelsManager', function () {
         return new ModelsManager();
     });
 }
예제 #7
0
        });
        $db->setEventsManager($eventsManager);
    }
    return $db;
});
$di->setShared('dbSlave', function () use($config) {
    $db = new DbAdapter(['host' => $config->db->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'charset' => $config->database->charset, "options" => [PDO::ATTR_TIMEOUT => "1"]]);
    if ($config->debug) {
        $eventsManager = new EventsManager();
        $logger = new FileLogger(PROJ_DIR . '/common/logs/debug.log');
        $eventsManager->attach('db', function ($event, $connection) use($logger) {
            if ($event->getType() == 'beforeQuery') {
                $logger->log($connection->getSQLStatement(), Logger::INFO);
            }
        });
        $db->setEventsManager($eventsManager);
    }
    return $db;
});
/**
 * /**
 * debug模式不缓存
 */
$di->set('modelsMetadata', function () use($config) {
    if ($config->debug) {
        return new MetaDataMemory();
    } else {
        return new MetaDataFiles(['metaDataDir' => PROJ_DIR . '/common/cache/metadata/']);
    }
});
/**
예제 #8
0
  * DATABASE
  */
 $di['db'] = function () use($config, $di) {
     $logger = $di['logger'];
     $eventsManager = new PhEventsManager();
     // Listen all the database events
     $eventsManager->attach('db', function ($event, $connection) use($logger) {
         if ($event->getType() == 'beforeQuery') {
             $logger->log($connection->getSQLStatement(), PhLogger::INFO);
         }
     });
     $params = ["host" => $config->app_db->host, "username" => $config->app_db->username, "password" => $config->app_db->password, "dbname" => $config->app_db->name, "charset" => 'utf8'];
     $conn = new PhMysql($params);
     // Set everything to UTF8
     $conn->execute('SET NAMES UTF8', []);
     $conn->setEventsManager($eventsManager);
     return $conn;
 };
 /**
  * If the configuration specify the use of metadata adapter use it
  * or use memory otherwise
  */
 $di['modelsMetadata'] = function () use($config) {
     $metaData = new PhMetadataFiles(['metaDataDir' => ROOT_PATH . $config->app_model->metadata]);
     //Set a custom meta-data database introspection
     $metaData->setStrategy(new FlyAnnotationsMetaDataInitializer());
     return $metaData;
 };
 $di['modelsManager'] = function () {
     $eventsManager = new PhEventsManager();
     $modelsManager = new PhModelsManager();
예제 #9
0
 /**
  * Register cache, database, auth object and global requestBody (For HTTP body)
  * @param  Phalcon\DI $di
  * @throws \Modules\Core\Exceptions\HTTPException
  * @return void
  */
 private function registerServices($di)
 {
     /**
      * Starting cache (Memcached)
      */
     $di->set('cache', function () {
         $di = DI::getDefault();
         $frontCache = new \Phalcon\Cache\Frontend\Data(array('lifetime' => $di->get('config')->memcached->lifetime));
         $cache = new \Phalcon\Cache\Backend\Libmemcached($frontCache, array('servers' => array('host' => $di->get('config')->memcached->host, 'port' => $di->get('config')->memcached->port, 'weight' => $di->get('config')->memcached->weight)));
         return $cache;
     });
     /**
      * Initialize database object
      */
     $di->set('db', function () {
         $di = DI::getDefault();
         $adapter = new Database(array('host' => $di->get('config')->db->host, 'username' => $di->get('config')->db->username, 'password' => $di->get('config')->db->password, 'dbname' => $di->get('config')->db->dbname));
         // Added to log and debug sql queries
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('db', new Listener());
         $adapter->setEventsManager($eventsManager);
         return $adapter;
     });
     /**
      * Service to read HTTP body from requests
      */
     $di->setShared('requestBody', function () {
         $in = file_get_contents('php://input');
         $in = json_decode($in, false);
         if ($in === null) {
             throw new \Modules\Core\Exceptions\HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'appCode' => 'REQ1000', 'more' => ''));
         }
         return $in;
     });
     /**
      * Service to use authin a global way
      */
     $di->setShared('auth', function () {
         $di = DI::getDefault();
         $crypt = new Crypt();
         //This method probably is not available if you use php-fpm
         //@todo, implement it
         $headers = getallheaders();
         if (!isset($headers['Authorization'])) {
             $msg = 'Token not provided';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         }
         set_error_handler(function () {
             $msg = 'Invalid access token';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         });
         $token = pack('H*', $headers['Authorization']);
         if (!$token) {
             $msg = 'Wrong access token';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         }
         $token = $crypt->decrypt($token, $di->get('config')->app->crypkey);
         $tokens = explode('|', $token);
         if ($tokens[2] != $_SERVER['REMOTE_ADDR']) {
             $msg = 'Wrong token (Ip address)';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         }
         if ($tokens[3] != $_SERVER['HTTP_USER_AGENT']) {
             $msg = 'Wrong access token (User agent)';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         }
         if ($tokens[4] < time()) {
             $msg = 'Token has expiried';
             throw new \Modules\Core\Exceptions\HTTPException($msg, 401);
         }
         return true;
     });
 }
예제 #10
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     $config = $this->config;
     $debug = $this->debug;
     /**
      * Setting up the view component
      */
     $DD = $this::DIR;
     $di['view'] = function () use($config, $debug, $DD) {
         $view = new View();
         $viewDir = $DD . '/views/';
         if ($config->offsetExists('application') && $config->application->offsetExists('viewsDir') && $config->application->offsetExists('viewsDir')) {
             $viewDir = $config->application->viewsDir;
         }
         $view->setViewsDir($viewDir);
         $viewEngines = ['.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'];
         $viewEngines['.volt'] = function ($view, $di) use($config, $debug, $DD) {
             $cacheDir = $DD . '/../cache/';
             $appConfig = $di['appConfig'];
             if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('cacheDir')) {
                 $cacheDir = $appConfig->volt->cacheDir;
             } elseif ($config->offsetExists('application') && $config->application->offsetExists('cacheDir') && $config->application->offsetExists('cacheDir')) {
                 $cacheDir = $config->application->cacheDir;
             }
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(array('compiledPath' => $cacheDir, 'compiledExtension' => ".compiled", 'compiledSeparator' => '_', 'compileAlways' => $debug));
             $compiler = $volt->getCompiler();
             // 扩展
             if ($config->offsetExists('volt') && $config->volt->offsetExists('extension')) {
                 foreach ($config->volt->extension as $k => $v) {
                     $compiler->addExtension($v);
                 }
             }
             if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('extension')) {
                 foreach ($appConfig->volt->extension as $k => $v) {
                     $compiler->addExtension($v);
                 }
             }
             // 函数
             if ($config->offsetExists('volt') && $config->volt->offsetExists('func')) {
                 foreach ($config->volt->func as $k => $v) {
                     $compiler->addFunction($k, $v);
                 }
             }
             if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('func')) {
                 foreach ($appConfig->volt->func as $k => $v) {
                     $compiler->addFunction($k, $v);
                 }
             }
             // 过滤器
             if ($config->offsetExists('volt') && $config->volt->offsetExists('filter')) {
                 foreach ($config->volt->filter as $k => $v) {
                     $compiler->addFilter($k, $v);
                 }
             }
             if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('filter')) {
                 foreach ($appConfig->volt->filter as $k => $v) {
                     $compiler->addFilter($k, $v);
                 }
             }
             return $volt;
         };
         $view->registerEngines($viewEngines);
         return $view;
     };
     if ($config->offsetExists('database')) {
         $di['db'] = function () use($config, $di, $debug) {
             $appConfig = $di['appConfig'];
             if ($debug && $appConfig->offsetExists('logger') && $appConfig->logger->offsetExists('sqlPath')) {
                 $eventsManager = new EventsManager();
                 $path = $config->logger->sqlPath;
                 $path = str_replace('{{date}}', date("Ymd"), $path);
                 $logger = new LoggerFile($path);
                 //Listen all the database events
                 $eventsManager->attach('db', function ($event, $connection) use($logger) {
                     if ($event->getType() == 'beforeQuery') {
                         $logger->log($connection->getSQLStatement(), Logger::INFO);
                     }
                 });
                 $connection = new DbAdapter($config->database->toArray());
                 //Assign the eventsManager to the db adapter instance
                 $connection->setEventsManager($eventsManager);
                 return $connection;
             } else {
                 return new DbAdapter($config->database->toArray());
             }
         };
     }
     if ($config->offsetExists('application') && $config->application->offsetExists('baseUri')) {
         $di['url'] = function () use($config) {
             $url = new \Phalcon\Mvc\Url();
             $url->setBaseUri($config->application->baseUri);
             return $url;
         };
     }
     $di['moduleConfig'] = function () use($config) {
         return $config;
     };
 }
예제 #11
0
 /**
  * set the database connection under db
  */
 protected function initDatabase()
 {
     $config = $this->di->get('config');
     $logger = $this->di->get('logger');
     $debug = isset($config->app->debug) ? (bool) $config->app->debug : false;
     $this->di->set('db', function () use($config, $debug, $logger) {
         $params = ['host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->name];
         $connection = new PhDbAdapter($params);
         if ($debug) {
             $eventsManager = new PhEventsManager();
             $eventsManager->attach('db', function (PhEvent $event, PhDbAdapter $connection) use($logger) {
                 if ($event->getType() == 'beforeQuery') {
                     $logger->log($connection->getSQLStatement(), PhLogger::INFO);
                 }
             });
             $connection->setEventsManager($eventsManager);
         }
         return $connection;
     });
 }
예제 #12
0
 protected function initDb()
 {
     $di = $this->getDi();
     // Setup the database service
     $di->set('db', function () {
         $config = $this->getConfig()['database'];
         $eventsManager = new EventsManager();
         $logger = new FileLogger(ROOT . $this->getConfig()['apps_data']['tmp_path'] . '/' . date('Y-m-d') . '.sql.log');
         // Listen all the database events
         $eventsManager->attach('db', function ($event, $connection) use($logger) {
             if ($event->getType() == 'beforeQuery') {
                 $logger->info($connection->getSQLStatement());
             }
         });
         $db = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
         // $db->query('set names utf-8');
         $db->setEventsManager($eventsManager);
         return $db;
     });
 }
예제 #13
0
 private static function registCommonService($di, $config)
 {
     $di->setShared('config', $config);
     $di->setShared('profiler', function () {
         return new \Phalcon\Db\Profiler();
     });
     $di->setShared('modelsMetadata', function () use($di, $config) {
         if ('file' == $config->metaData->saveType) {
             $savePath = $config->metaData->savePath;
             if (!file_exists($savePath)) {
                 mkdir($savePath, 0744, true);
             }
             $metaData = new \Phalcon\Mvc\Model\Metadata\Files(array('metaDataDir' => $savePath));
             return $metaData;
         }
     });
     $di->setShared('db_myPhalcon_w', function () use($di, $config) {
         $profiler = $di->getProfiler();
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('db', function ($event, $connection) use($profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes());
             }
             if ($event->getType() == 'afterQuery') {
                 $profiler->stopProfile();
                 $profile = $profiler->getLastProfile();
                 LoggerUtil::info(sprintf('SQL %s , cost time : %s', $profile->getSQLStatement(), $profile->getTotalElapsedSeconds()));
             }
         });
         $db = new DbAdapter(array('host' => $config->mysql->myPhalcon_w->host, 'username' => $config->mysql->myPhalcon_w->username, 'password' => $config->mysql->myPhalcon_w->password, 'dbname' => $config->mysql->myPhalcon_w->dbname, 'port' => $config->mysql->myPhalcon_w->port));
         $db->setEventsManager($eventsManager);
         return $db;
     });
     $di->setShared('db_myPhalcon_r', function () use($di, $config) {
         $profiler = $di->getProfiler();
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('db', function ($event, $connection) use($profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes());
             }
             if ($event->getType() == 'afterQuery') {
                 $profiler->stopProfile();
                 $profile = $profiler->getLastProfile();
                 LoggerUtil::info(sprintf('SQL: %s , COST TIME: %s', $profile->getSQLStatement(), $profile->getTotalElapsedSeconds()));
             }
         });
         $db = new DbAdapter(array('host' => $config->mysql->myPhalcon_r->host, 'username' => $config->mysql->myPhalcon_r->username, 'password' => $config->mysql->myPhalcon_r->password, 'dbname' => $config->mysql->myPhalcon_r->dbname, 'port' => $config->mysql->myPhalcon_r->port));
         $db->setEventsManager($eventsManager);
         return $db;
     });
     $di->setShared('redisCache', function () use($di, $config) {
         require VENDOR_PATH . '/predis/Autoloader.php';
         \Predis\Autoloader::register();
         $host = $config->redisCache->host;
         $port = $config->redisCache->port;
         return new \Predis\Client("tcp://{$host}:{$port}");
     });
     $di->setShared('curl', function () use($di, $config) {
         require VENDOR_PATH . '/Curl/Autoloader.php';
         \Curl\Autoloader::register();
         return new \Curl\Curl();
     });
     $di->setShared('image', function () use($di, $config) {
         require VENDOR_PATH . '/Image/Autoloader.php';
         \Image\Autoloader::register();
         return new \Image\Image(\Image\Image::IMAGE_IMAGICK);
     });
 }
예제 #14
0
 /**
  * 数据库连接
  */
 protected function initDatabase()
 {
     $config = $this->config;
     $debug = $this->debug;
     if ($config->offsetExists('database') == false) {
         return;
     }
     $this->di['db'] = function () use($config, $debug) {
         if ($debug && $config->offsetExists('logger') && $config->logger->offsetExists('sqlPath')) {
             $eventsManager = new EventsManager();
             $path = $config->logger->sqlPath;
             $path = str_replace('{{date}}', date("Ymd"), $path);
             $logger = new LoggerFile($path);
             //Listen all the database events
             $eventsManager->attach('db', function ($event, $connection) use($logger) {
                 if ($event->getType() == 'beforeQuery') {
                     $logger->log($connection->getSQLStatement(), Logger::INFO);
                 }
             });
             $connection = new DbAdapter($config->database->toArray());
             //Assign the eventsManager to the db adapter instance
             $connection->setEventsManager($eventsManager);
             return $connection;
         } else {
             return new DbAdapter($config->database->toArray());
         }
     };
 }
 /**
  * Initializes the database and netadata adapter
  *
  * @param array $options
  */
 protected function initDatabase($options = array())
 {
     $config = $this->_di->get('config');
     $logger = $this->_di->get('logger');
     $debug = isset($config->app->debug) ? (bool) $config->app->debug : false;
     $this->_di->set('db', function () use($debug, $config, $logger) {
         if ($debug) {
             $eventsManager = new PhEventsManager();
             // Listen all the database events
             $eventsManager->attach('db', function ($event, $connection) use($logger) {
                 if ($event->getType() == 'beforeQuery') {
                     $logger->log($connection->getSQLStatement(), PhLogger::INFO);
                 }
             });
         }
         $params = array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name);
         $conn = new PhMysql($params);
         if ($debug) {
             // Assign the eventsManager to the db adapter instance
             $conn->setEventsManager($eventsManager);
         }
         return $conn;
     });
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $this->_di->set('modelsMetadata', function () use($config) {
         if (isset($config->app->metadata)) {
             if ($config->app->metadata->adapter == 'Files') {
                 return new PhMetadataFiles(array('metaDataDir' => $config->app->metadata->path));
             } else {
                 return new PhMetadataMemory();
             }
         } else {
             return new PhMetadataMemory();
         }
     });
     $test = $this->_di->get('modelsMetadata');
 }
        $logger = new FileLogger(APP_PATH . "/app/logs/db.log");
        //Listen all the database events
        $eventsManager->attach('db', function ($event, $connection) use($logger) {
            /** @var Phalcon\Events\Event $event */
            if ($event->getType() == 'beforeQuery') {
                /** @var DatabaseConnection $connection */
                $variables = $connection->getSQLVariables();
                if ($variables) {
                    $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO);
                } else {
                    $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
                }
            }
        });
        //Assign the eventsManager to the db adapter instance
        $connection->setEventsManager($eventsManager);
    }
    return $connection;
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->set('modelsMetadata', function () use($config) {
    if ($config->application->debug) {
        return new MemoryMetaDataAdapter();
    }
    return new MetaDataAdapter(['metaDataDir' => APP_PATH . '/app/cache/metaData/']);
}, true);
/**
 * Start the session the first time some component request the session service
 */
예제 #17
0
 protected function initDb()
 {
     $config = $this->di['config'];
     $profiler = $this->di['profiler'];
     $this->di->set('db', function () use($config, $profiler) {
         // set up the database adapter
         $adapter = new DbAdapter(['host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'persistent' => $config->database->persistent]);
         if ($config->profiling->query) {
             $eventsManager = new \Phalcon\Events\Manager();
             // listen to all the database events
             $eventsManager->attach('db', function ($event, $connection) use($profiler) {
                 if ($event->getType() == 'beforeQuery') {
                     $profiler->startProfile($connection->getSQLStatement());
                 }
                 if ($event->getType() == 'afterQuery') {
                     $profiler->stopProfile();
                 }
             });
             $adapter->setEventsManager($eventsManager);
         }
         return $adapter;
     }, TRUE);
 }