예제 #1
0
 public function afterQuery($event, $connection)
 {
     $this->dbProfiler->stopProfile();
     $this->queries[] = ['query' => $connection->getSQLStatement(), 'time' => $this->dbProfiler->getTotalElapsedSeconds()];
     $this->dbProfiler->reset();
     ++$this->counter;
 }
예제 #2
0
 /**
  * 注册Profiler,监听DB
  * @param   $dblist 监听的db列表,默认监听db
  * @return [type] [description]
  */
 public static function registerDbprofiler($dblist = array('db'))
 {
     if (DI::getDefault()['request']->hasQuery('debug') && APP_ENV != 'product') {
         $profiler = new Profiler();
         $di = DI::getDefault();
         $di->setShared('profiler', function () use($profiler) {
             return $profiler;
         });
         foreach ($dblist as $value) {
             $eventsManager = new Manager();
             $connection = $di[$value];
             $eventsManager->attach('db', function ($event, $connection) use($profiler) {
                 //一条语句查询之前事件,profiler开始记录sql语句
                 if ($event->getType() == 'beforeQuery') {
                     $profiler->startProfile($connection->getSQLStatement());
                 }
                 //一条语句查询结束,结束本次记录,记录结果会保存在profiler对象中
                 if ($event->getType() == 'afterQuery') {
                     $profiler->stopProfile();
                 }
             });
             //将事件管理器绑定到db实例中
             $connection->setEventsManager($eventsManager);
         }
     }
 }
예제 #3
0
 /**
  * @param Event $event
  * @param DbAdapterInterface $connection
  */
 public function afterQuery(Event $event, DbAdapterInterface $connection)
 {
     $this->_profiler->stopProfile();
     $sqlVariables = $connection->getSQLVariables() ?: [];
     foreach ($sqlVariables as $key => $value) {
         if ($key[0] !== ':') {
             unset($sqlVariables[$key]);
             $key = ':' . $key;
         }
         $sqlVariables[$key] = !is_array($value) ? $connection->escapeString((string) $value) : array_map(function ($v) use($connection) {
             return $connection->escapeString((string) $v);
             // important
         }, $value);
     }
     $statement = strtr($connection->getRealSQLStatement(), $sqlVariables);
     $time = $this->_profiler->getTotalElapsedSeconds() - $this->_previousTotalExecutionTime;
     $this->_previousTotalExecutionTime = $this->_profiler->getTotalElapsedSeconds();
     $this->_logger->log(sprintf('%s [Execution time: %.4f sec.]', $statement, round($time, 4)), $this->_priority);
 }
예제 #4
0
<?php

use Phalcon\Events\Manager as EventsManager, Phalcon\Db\Profiler as DbProfiler;
$eventsManager = new EventsManager();
$profiler = new DbProfiler();
//Listen all the database events
$eventsManager->attach('db', function ($event, $connection) use($profiler) {
    if ($event->getType() == 'beforeQuery') {
        //Start a profile with the active connection
        $profiler->startProfile($connection->getSQLStatement());
    }
    if ($event->getType() == 'afterQuery') {
        //Stop the active profile
        $profiler->stopProfile();
    }
});
//Assign the events manager to the connection
$connection->setEventsManager($eventsManager);
$sql = "SELECT buyer_name, quantity, product_name " . "FROM buyers " . "LEFT JOIN products ON buyers.pid = products.id";
// Execute a SQL statement
$connection->query($sql);
// Get the last profile in the profiler
$profile = $profiler->getLastProfile();
echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
예제 #5
0
 /**
  * Init database.
  *
  * @param DI            $di            Dependency Injection.
  * @param Config        $config        Config object.
  * @param EventsManager $eventsManager Event manager.
  *
  * @return Pdo
  */
 protected function _initDb($di, $config, $eventsManager)
 {
     $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config->db->mysql->adapter;
     /** @var Pdo $connection */
     $connection = new $adapter(['host' => $config->db->mysql->host, 'port' => $config->db->mysql->port, 'username' => $config->db->mysql->username, 'password' => $config->db->mysql->password, 'dbname' => $config->db->mysql->dbname]);
     $isProfiler = $config->global->profiler;
     if ($isProfiler) {
         // Attach logger & profiler.
         $profiler = null;
         if ($isProfiler) {
             $profiler = new PhDbProfiler();
         }
         $eventsManager->attach('db', function ($event, $connection) use($profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $statement = $connection->getSQLStatement();
                 if ($profiler) {
                     $profiler->startProfile($statement);
                 }
             }
             if ($event->getType() == 'afterQuery') {
                 // Stop the active profile.
                 if ($profiler) {
                     $profiler->stopProfile();
                 }
             }
         });
         if ($profiler && $di->has('profiler')) {
             $di->get('profiler')->setDbProfiler($profiler);
         }
         $connection->setEventsManager($eventsManager);
     }
     $di->set('db', $connection);
     /**
      * Add db service connect to five.vn database
      */
     $di->set('dbfive', function () use($config) {
         $fiveAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config->db->dbfive->adapter;
         return new $fiveAdapter(['host' => $config->db->dbfive->host, 'port' => $config->db->dbfive->port, 'username' => $config->db->dbfive->username, 'password' => $config->db->dbfive->password, 'dbname' => $config->db->dbfive->dbname]);
     });
     $di->set('modelsManager', function () use($config, $eventsManager) {
         $modelsManager = new PhModelsManager();
         $modelsManager->setEventsManager($eventsManager);
         // Attach a listener to models-manager
         $eventsManager->attach('modelsManager', new ModelAnnotationsInitializer());
         return $modelsManager;
     }, true);
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise.
      */
     $di->set('modelsMetadata', function () use($config) {
         if (ENV == ENV_PRODUCTION && isset($config->global->metadata)) {
             $metaDataConfig = $config->global->metadata;
             $metadataAdapter = '\\Phalcon\\Mvc\\Model\\Metadata\\' . $metaDataConfig->adapter;
             $metaData = new $metadataAdapter($config->global->metadata->toArray());
         } else {
             $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
         }
         $metaData->setStrategy(new PhStrategyAnnotations());
         return $metaData;
     }, true);
     return $connection;
 }
예제 #6
0
 /**
  * Init database.
  *
  * @param DI            $di            Dependency Injection.
  * @param Config        $config        Config object.
  * @param EventsManager $eventsManager Event manager.
  *
  * @return Pdo
  */
 protected function _initDatabase($di, $config, $eventsManager)
 {
     if (!$config->installed) {
         return;
     }
     $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config->database->adapter;
     /** @var Pdo $connection */
     $connection = new $adapter(["host" => $config->database->host, "port" => $config->database->port, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname]);
     $isDebug = $config->application->debug;
     $isProfiler = $config->application->profiler;
     if ($isDebug || $isProfiler) {
         // Attach logger & profiler.
         $logger = null;
         $profiler = null;
         if ($isDebug) {
             $logger = new File($config->application->logger->path . "db.log");
         }
         if ($isProfiler) {
             $profiler = new DatabaseProfiler();
         }
         $eventsManager->attach('db', function ($event, $connection) use($logger, $profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $statement = $connection->getSQLStatement();
                 if ($logger) {
                     $logger->log($statement, Logger::INFO);
                 }
                 if ($profiler) {
                     $profiler->startProfile($statement);
                 }
             }
             if ($event->getType() == 'afterQuery') {
                 // Stop the active profile.
                 if ($profiler) {
                     $profiler->stopProfile();
                 }
             }
         });
         if ($profiler && $di->has('profiler')) {
             $di->get('profiler')->setDbProfiler($profiler);
         }
         $connection->setEventsManager($eventsManager);
     }
     $di->set('db', $connection);
     $di->set('modelsManager', function () use($config, $eventsManager) {
         $modelsManager = new ModelsManager();
         $modelsManager->setEventsManager($eventsManager);
         // Attach a listener to models-manager
         $eventsManager->attach('modelsManager', new ModelAnnotationsInitializer());
         return $modelsManager;
     }, true);
     /**
      * 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 && isset($config->application->metadata)) {
             $metaDataConfig = $config->application->metadata;
             $metadataAdapter = '\\Phalcon\\Mvc\\Model\\Metadata\\' . $metaDataConfig->adapter;
             $metaData = new $metadataAdapter($config->application->metadata->toArray());
         } else {
             $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
         }
         $metaData->setStrategy(new StrategyAnnotations());
         return $metaData;
     }, true);
     return $connection;
 }