Exemplo n.º 1
0
 public function afterQuery($event, $connection)
 {
     $this->dbProfiler->stopProfile();
     $this->queries[] = ['query' => $connection->getSQLStatement(), 'time' => $this->dbProfiler->getTotalElapsedSeconds()];
     $this->dbProfiler->reset();
     ++$this->counter;
 }
Exemplo n.º 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);
         }
     }
 }
Exemplo n.º 3
0
 public function __destruct()
 {
     if ($this->_logger && $this->_profiler) {
         $this->_logger->log(sprintf('Total SQL execution time (%d queries): %.4f sec.', $this->_profiler->getNumberTotalStatements(), round($this->_profiler->getTotalElapsedSeconds(), 4)), $this->_priority);
         $this->_logger->commit();
     }
 }
Exemplo n.º 4
0
 /**
  * Get html for sql section.
  *
  * @param \Phalcon\Db\Profiler $dbProfiler         Database profiler.
  * @param int                  $totalSqlStatements Total count.
  *
  * @return string
  */
 private function _getHtmlSql($dbProfiler, $totalSqlStatements)
 {
     $html = 'No Sql';
     $dbProfiles = $dbProfiler->getProfiles();
     if (!empty($dbProfiles)) {
         $longestQuery = '';
         $longestQueryTime = 0;
         $html = $this->_viewRenderElement('Total count', $totalSqlStatements, null, true);
         $html .= $this->_viewRenderElement('Total time', round($dbProfiler->getTotalElapsedSeconds() * 1000, 4), null, true);
         $html .= $this->_viewRenderElement('Longest query', '<span class="code">%s</span> (%s ms)<br/>', null, true);
         foreach ($dbProfiles as $profile) {
             if ($profile->getTotalElapsedSeconds() > $longestQueryTime) {
                 $longestQueryTime = $profile->getTotalElapsedSeconds();
                 $longestQuery = $profile->getSQLStatement();
             }
             $html .= $this->_viewRenderElement('SQL', $profile->getSQLStatement());
             $html .= $this->_viewRenderElement('Time', round($profile->getTotalElapsedSeconds() * 1000, 4) . ' ms<br/>', null, true);
         }
         $html = sprintf($html, $longestQuery, round($longestQueryTime * 1000, 4));
     }
     return $html;
 }
Exemplo n.º 5
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";
Exemplo n.º 6
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;
 }
Exemplo n.º 7
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;
 }