Esempio n. 1
0
<?php

$eventsManager = new \Phalcon\Events\Manager();
$profiler = new \Phalcon\Db\Profiler();
//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";
Esempio n. 2
0
 /**
  * Initializes the database and metadata adapter
  */
 public function init()
 {
     $di = $this->getDi();
     $eventsManager = $this->getEventsManager();
     $config = $this->_config;
     $adapter = $this->_getDatabaseAdapter($config->database->adapter);
     if (!$adapter) {
         throw new \Engine\Exception("Database adapter '{$config->database->adapter}' not exists!");
     }
     $connection = new $adapter(["host" => $this->_config->database->host, "username" => $this->_config->database->username, "password" => $this->_config->database->password, "dbname" => $this->_config->database->dbname, "options" => [\PDO::ATTR_EMULATE_PREPARES => false]]);
     if (!$config->application->debug && $config->database->useCache) {
         if ($di->offsetExists('modelsCache')) {
             //$connection->setCache($di->get('modelsCache'));
         }
     }
     if ($config->application->debug) {
         // Attach logger & profiler
         $logger = new \Phalcon\Logger\Adapter\File($config->application->logger->path . "db.log");
         $profiler = new \Phalcon\Db\Profiler();
         $eventsManager->attach('db', function ($event, $connection) use($logger, $profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $statement = $connection->getSQLStatement();
                 $logger->log($statement, \Phalcon\Logger::INFO);
                 $profiler->startProfile($statement);
             }
             if ($event->getType() == 'afterQuery') {
                 //Stop the active profile
                 $profiler->stopProfile();
             }
         });
         if ($this->_config->application->profiler && $di->has('profiler')) {
             $di->get('profiler')->setDbProfiler($profiler);
         }
         $connection->setEventsManager($eventsManager);
     }
     $di->set('db', $connection);
     if (isset($config->database->useAnnotations) && $config->database->useAnnotations) {
         $di->set('modelsManager', function () use($config, $eventsManager) {
             $modelsManager = new \Phalcon\Mvc\Model\Manager();
             $modelsManager->setEventsManager($eventsManager);
             //Attach a listener to models-manager
             $eventsManager->attach('modelsManager', new \Engine\Model\AnnotationsInitializer());
             return $modelsManager;
         }, true);
     }
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $service = $this;
     $di->set('modelsMetadata', function () use($config, $service) {
         if ((!$config->application->debug || $config->application->useCachingInDebugMode) && isset($config->metadata)) {
             $metaDataConfig = $config->metadata;
             $metadataAdapter = $service->_getMetaDataAdapter($metaDataConfig->adapter);
             if (!$metadataAdapter) {
                 throw new \Engine\Exception("MetaData adapter '{$metaDataConfig->adapter}' not exists!");
             }
             $metaData = new $metadataAdapter($config->metadata->toArray());
         } else {
             $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
         }
         if (isset($config->database->useAnnotations) && $config->database->useAnnotations) {
             $metaData->setStrategy(new \Engine\Model\AnnotationsMetaDataInitializer());
         }
         return $metaData;
     }, true);
 }
Esempio n. 3
0
 public function run()
 {
     $di = new \Phalcon\DI\FactoryDefault();
     $config = (include APPLICATION_PATH . '/config/application.php');
     $di->set('config', $config);
     $registry = new \Phalcon\Registry();
     $loader = new \Phalcon\Loader();
     $loader->registerNamespaces($config->loader->namespaces->toArray());
     $loader->register();
     $loader->registerDirs(array(APPLICATION_PATH . "/plugins/"));
     $db = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset));
     $di->set('db', $db);
     $view = new \Phalcon\Mvc\View();
     define('MAIN_VIEW_PATH', '../../../views/');
     $view->setMainView(MAIN_VIEW_PATH . 'main');
     $view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/');
     $view->setPartialsDir(MAIN_VIEW_PATH . '/partials/');
     $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
     $volt->setOptions(array('compiledPath' => APPLICATION_PATH . '/cache/volt/'));
     $phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di);
     $viewEngines = array(".volt" => $volt, ".phtml" => $phtml);
     $registry->viewEngines = $viewEngines;
     $view->registerEngines($viewEngines);
     if (isset($_GET['_ajax']) && $_GET['_ajax']) {
         $view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
     }
     $di->set('view', $view);
     $viewSimple = new \Phalcon\Mvc\View\Simple();
     $viewSimple->registerEngines($viewEngines);
     $di->set('viewSimple', $viewSimple);
     $url = new \Phalcon\Mvc\Url();
     $url->setBasePath('/');
     $url->setBaseUri('/');
     $cacheFrontend = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 60, "prefix" => HOST_HASH));
     switch ($config->cache) {
         case 'file':
             $cache = new \Phalcon\Cache\Backend\File($cacheFrontend, array("cacheDir" => __DIR__ . "/cache/backend/"));
             break;
         case 'memcache':
             $cache = new \Phalcon\Cache\Backend\Memcache($cacheFrontend, array("host" => "localhost", "port" => "11211"));
             break;
     }
     $di->set('cache', $cache);
     $di->set('modelsCache', $cache);
     switch ($config->metadata_cache) {
         case 'memory':
             $modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory();
             break;
         case 'apc':
             $modelsMetadata = new \Phalcon\Mvc\Model\MetaData\Apc(array("lifetime" => 60, "prefix" => HOST_HASH));
             break;
     }
     $di->set('modelsMetadata', $modelsMetadata);
     /**
      * CMS Конфигурация
      */
     $cmsModel = new \Cms\Model\Configuration();
     $cms = $cmsModel->getConfig();
     // @todo Будет отдельный раздел конфигурации для управления языками. Пока заглушка.
     $cms['languages'] = [['name' => 'Русский', 'iso' => 'ru', 'locale' => 'ru_RU'], ['name' => 'English', 'iso' => 'en', 'locale' => 'en_EN']];
     $registry->cms = $cms;
     // Отправляем в Registry
     $application = new \Phalcon\Mvc\Application();
     $application->registerModules($config->modules->toArray());
     $router = new \Application\Mvc\Router\DefaultRouter();
     foreach ($application->getModules() as $module) {
         $className = str_replace('Module', 'Routes', $module['className']);
         if (class_exists($className)) {
             $class = new $className();
             $router = $class->init($router);
         }
     }
     $di->set('router', $router);
     $eventsManager = new \Phalcon\Events\Manager();
     $dispatcher = new \Phalcon\Mvc\Dispatcher();
     $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher, $di) use($di) {
         new LocalizationPlugin($dispatcher);
         new AclPlugin($di->get('acl'), $dispatcher);
     });
     $profiler = new \Phalcon\Db\Profiler();
     $eventsManager->attach('db', function ($event, $db) use($profiler) {
         if ($event->getType() == 'beforeQuery') {
             $profiler->startProfile($db->getSQLStatement());
         }
         if ($event->getType() == 'afterQuery') {
             $profiler->stopProfile();
         }
     });
     $db->setEventsManager($eventsManager);
     $di->set('profiler', $profiler);
     $dispatcher->setEventsManager($eventsManager);
     $di->set('dispatcher', $dispatcher);
     $session = new \Phalcon\Session\Adapter\Files();
     $session->start();
     $di->set('session', $session);
     $acl = new \Application\Acl\DefaultAcl();
     $di->set('acl', $acl);
     $assets = new \Phalcon\Assets\Manager();
     $di->set('assets', $assets);
     $flash = new \Phalcon\Flash\Session(array('error' => 'ui red inverted segment', 'success' => 'ui green inverted segment', 'notice' => 'ui blue inverted segment', 'warning' => 'ui orange inverted segment'));
     $di->set('flash', $flash);
     $di->set('helper', new \Application\Mvc\Helper());
     $di->set('registry', $registry);
     $assetsManager = new \Phalcon\Assets\Manager();
     $di->set('assets', $assetsManager);
     $application->setDI($di);
     $this->dispatch($di);
 }