예제 #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;
 }
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    $connection = new DatabaseConnection($config->database->toArray());
    $debug = $config->application->debug;
    if ($debug) {
        $eventsManager = new EventsManager();
        $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) {
예제 #4
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;
     };
 }
예제 #5
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);
 }
예제 #6
0
파일: services.php 프로젝트: kjmtrue/forum
    $view->registerEngines([".volt" => 'volt']);
    return $view;
}, true);
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config, $di) {
    $connection = new DatabaseConnection($config->database->toArray());
    $eventsManager = new EventsManager();
    // Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use($di) {
        /** @var Phalcon\Events\Event $event */
        if ($event->getType() == 'beforeQuery') {
            /** @var DatabaseConnection $connection */
            $variables = $connection->getSQLVariables();
            $string = $connection->getSQLStatement();
            if ($variables) {
                $string .= ' [' . join(',', $variables) . ']';
            }
            // To disable logging change logLevel in config
            $di->get('logger', ['db.log'])->debug($string);
        }
    });
    // Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);
    return $connection;
});
/**
 * Queue to deliver e-mails in real-time
 */
$di->set('queue', function () use($config) {
예제 #7
0
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Cache\Multiple;
use Phalcon\Cache\Backend\Apc as ApcCache;
use Phalcon\Cache\Backend\File as FileCache;
use Phalcon\Cache\Frontend\Data as DataFrontend;
use Phalcon\Logger;
use Phalcon\Events\Manager as EventsManager;
$di = new Phalcon\DI\FactoryDefault();
//mysql
$di->set("db", function () use($mysql_config) {
    $connection = new PdoMysql(array("host" => $mysql_config['host'], "username" => $mysql_config['username'], "password" => $mysql_config['password'], "dbname" => $mysql_config['dbname'], "options" => array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'", PDO::ATTR_CASE => PDO::CASE_LOWER)));
    $eventsManager = new EventsManager();
    $logger = new LoggerFile(getLogFilePath(DB_LOOGER_DIR, DB_LOG_SIZE, 'db_logs_'));
    $eventsManager->attach('db', function ($event, $connection) use($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), Logger::INFO);
        }
    });
    $connection->setEventsManager($eventsManager);
    return $connection;
});
// Logger
$di->set('logger', function () {
    return new LoggerFile(getLogFilePath(LOOGER_DIR, LOG_SIZE, 'logs_'));
});
//Router
$di->set('router', function () {
    $router = (require __DIR__ . '/Route.php');
    return $router;
});
//view
예제 #8
0
 /**
  * @param       $event
  * @param Mysql $connection
  */
 public function afterQuery($event, Mysql $connection)
 {
     $this->logger->log($connection->getSQLStatement(), \Phalcon\Logger::ERROR);
 }
예제 #9
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;
     });
 }