Phalcon Framework 1.2.6

Phalcon\Logger\Exception: Can't open log file at '/var/www/html/ptmu/common/config/../../logs/20170221/sql_slave_profiler.log'

/var/www/html/ptmu/common/config/services.php (166)
#0Phalcon\Logger\Adapter\File->__construct(/var/www/html/ptmu/common/config/../../logs/20170221/sql_slave_profiler.log)
/var/www/html/ptmu/common/config/services.php (166)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#1{closure}(sql_slave_profiler)
#2Phalcon\DI\Service->resolve(Array([0] => sql_slave_profiler), Object(Phalcon\DI\FactoryDefault))
#3Phalcon\DI->get(fileLogger, Array([0] => sql_slave_profiler))
/var/www/html/ptmu/common/config/services.php (212)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#4{closure}(sql_slave)
#5Phalcon\DI\Service->resolve(Array([0] => sql_slave), Object(Phalcon\DI\FactoryDefault))
#6Phalcon\DI->get(dbEventManager, Array([0] => sql_slave))
/var/www/html/ptmu/common/config/services.php (309)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#7{closure}()
#8Phalcon\DI\Service->resolve(null, Object(Phalcon\DI\FactoryDefault))
#9Phalcon\DI->get(dbSlave)
/var/www/html/ptmu/common/library/ModelsManager/ModelsManager.php (54)
<?php
 
namespace PTMU\ModelsManager;
 
class ModelsManager extends \Phalcon\Mvc\Model\Manager {
 
  /**
   * Returns the connection service name used to write data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getWriteConnectionService ($model) { 
    return "dbMaster";
  }
 
  /**
   * Returns the connection service name used to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getReadConnectionService ($model) { 
    return "dbSlave";
  }
  
  /**
   * Returns the connection service name used to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getSphinxConnectionService ($model) { 
    return "dbSphinx";
  }
  
  /**
   * Returns the connection to write data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getWriteConnection ($model) {
    return $this->getDI ()->get ($this->getWriteConnectionService ($model));
  }
 
  /**
   * Returns the connection to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getReadConnection ($model) { 
    return $this->getDI ()->get ($this->getReadConnectionService ($model));
  }
  
  /**
   * Returns the connection to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getSphinxConnection ($model) { 
    return $this->getDI ()->get ($this->getSphinxConnectionService ($model));
  }
}
#10PTMU\ModelsManager\ModelsManager->getReadConnection(Object(PTMU\Models\Locations: ))
#11Phalcon\Mvc\Model->getReadConnection()
#12Phalcon\Mvc\Model\Query->_executeSelect(Array([models] => Array([0] => PTMU\Models\Locations), [tables] => Array([0] => locations), [columns] => Array([pTMU\Models\Locations] => Array([type] => object, [model] => PTMU\Models\Locations, [column] => locations, [balias] => pTMU\Models\Locations)), [where] => Array([type] => binary-op, [op] => =, [left] => Array([type] => qualified, [domain] => locations, [name] => Code, [balias] => code), [right] => Array([type] => placeholder, [value] => :0)), [limit] => Array([number] => 1)), Array([0] => united-kingdom), null)
#13Phalcon\Mvc\Model\Query->execute(Array([0] => united-kingdom), null)
#14Phalcon\Mvc\Model::findFirst(Array([conditions] => code = ?0, [bind] => Array([0] => united-kingdom)))
#15Phalcon\Mvc\Model::__callStatic(findFirstByCode, Array([0] => united-kingdom))
/var/www/html/ptmu/common/library/Location/Location.php (89)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#16PTMU\Models\Locations::findFirstByCode(united-kingdom)
/var/www/html/ptmu/common/library/Location/Location.php (89)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#17PTMU\Location\Location->setLocationByCode(united-kingdom)
/var/www/html/ptmu/common/library/Location/Location.php (26)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#18PTMU\Location\Location->__construct(united-kingdom)
/var/www/html/ptmu/common/config/services.php (478)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#19{closure}()
#20Phalcon\DI\Service->resolve(null, Object(Phalcon\DI\FactoryDefault))
#21Phalcon\DI->get(location, null)
#22Phalcon\DI->getShared(location)
#23Phalcon\DI\Injectable->__get(location)
/var/www/html/ptmu/frontend/controllers/SitemapController.php (38)
<?php
 
namespace PTMU\Frontend\Controllers;
use PTMU\Taxonomy as Taxonomy;
use PTMU\Taxonomy\Gender;
use PTMU\Taxonomy\AdAvailability;
use PTMU\Taxonomy\AdCategories as AdCategory;
use PTMU\Taxonomy\LocationType;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Utils\Utils;
use PTMU\Models\Locations;
 
class SitemapController extends ControllerBase {
  
  /**
   * index action
   */
  public function indexAction () {
    $category     = $this->getDispatcherParam ('category', 'int',    null);            
    $locationCode = $this->getDispatcherParam ('location', 'string', null);       
 
    $categoryName = '';      
    $locationName = '';
    $location     = null;
    $genders      = array ();
    $services     = array ();
 
    $topCaption   = $this->translations ['sitemap-default-caption'];
    $topLinkText  = '';    
    $topLinkUrl   = '';
    
    if (!is_null ($category)) {
      $taxonomyTree = TaxonomyModel::getTaxonomyAsTree ();
      $taxonomy     = TaxonomyModel::getTaxonomy ();
      $category     = $taxonomy [$category];
      $genders      = TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::GENDER);
      $services     = TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_AVAILABILITY);
      $location     = Locations::getLocation ($this->location->getID ());
      $categoryName = trim ($category ['name']);      
      
      $topCaption   = sprintf ($this->translations ['sitemap-category-caption'], $categoryName);
      $topLinkText  = sprintf ($this->translations ['sitemap-category-link'], $categoryName);      
      $topLinkUrl   = '/'. mb_strtolower ($category ['code']);
 
      if (!is_null ($locationCode)) {
        $location     = Locations::getLocation (Locations::getLocationIDByCode (null, $locationCode));
        $locationName = trim ($location ['name']);        
        
        $topCaption  = "{$locationName} {$categoryName}";
        $topLinkText = sprintf ($this->translations ['sitemap-category-in-link'], $categoryName, $locationName);;        
        $topLinkUrl  =  $topLinkUrl . '/' . mb_strtolower ($location ['code']);
      }
    }
 
    $categoryName = trim ("{$categoryName} {$locationName}");
    
    if (mb_strlen ($categoryName)) {
      $categoryName = " {$categoryName}";
    }
    
    $countKeys = [];
    if (is_null ($locationCode)) {
      foreach ($genders as $genderID => $genderName) {
        $countKeys [$genderID] = Utils::getCounterKey ($category ['taxonomyID'], $genderID);
      }
    }
    
    $this->view->setVar ('topCaption',                $topCaption);
    $this->view->setVar ('topLinkUrl',                $topLinkUrl);
    $this->view->setVar ('topLinkText',               $topLinkText);
    $this->view->setVar ('category',                  $category);
    $this->view->setVar ('location',                  $location);
    $this->view->setVar ('countKey',                  Utils::getCounterKey ($category ['taxonomyID'], Gender::GENDER_FEMALE));    
    $this->view->setVar ('countKeys',                 $countKeys);        
    $this->view->setVar ('locationCode',              $locationCode);
    $this->view->setVar ('genders',                   $genders);
    $this->view->setVar ('services',                  $services);
    $this->view->setVar ('taxFemale',                 Gender::GENDER_FEMALE);
    $this->view->setVar ('taxIncOutc',                AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS);
    $this->view->setVar ('locationTypeCounty',        $taxonomy [LocationType::COUNTY]);
    $this->view->setVar ('locationTypeMegalopolis',   $taxonomy [LocationType::MEGALOPOLIS]);
    $this->view->setVar ('locationTypeCityPart',      $taxonomy [LocationType::CITY_PART]);    
    $this->view->setVar ('locationTypeCity',          $taxonomy [LocationType::CITY]);    
    $this->view->setVar ('locationTypeNeighbourhood', $taxonomy [LocationType::NEIGHBOURHOOD]);        
    
    // Set proper application version for alternate/canonical link
    $this->view->setVar (Utils::getVersionVar (), true);
    
    // Page title and meta description          
    $this->view->setVar ("pageTitle",       sprintf ($this->translations ['sitemap-page-title'], $categoryName));
    $this->view->setVar ("metaDescription", sprintf ($this->translations ['sitemap-page-meta'], $categoryName));
  }
}
#24PTMU\Frontend\Controllers\SitemapController->indexAction(200002)
#25Phalcon\Dispatcher->dispatch()
#26Phalcon\Mvc\Application->handle()
/var/www/html/public/index.php (36)
<?php
  define('PINBA',(extension_loaded('pinba')?true:false));  
  error_reporting (E_ERROR | E_WARNING);
 
  // Global start time
  define ('APP_START_TIME', microtime (true));
    
  // Read the configuration
  $config = include (__DIR__ . "/../ptmu/common/config/config.php");
  
  // Define global application environment constant  
  define ('APPLICATION_ENV', (getenv ('APPLICATION_ENV') ? getenv ('APPLICATION_ENV') : $config->application->environment));
  
  // Read auto-loader
  include (__DIR__ . "/../ptmu/common/config/loader.php");
 
  // Read services
  include (__DIR__ . "/../ptmu/common/config/services.php");
 
  // Setup debugger
 
  $debug = new Phalcon\Debug ();
  $debug->listen ();
 
  // Handle the request
  $application = new \Phalcon\Mvc\Application ($di);
 
  // Registering modules  
  $application->registerModules (require (__DIR__ . '/../ptmu/common/config/modules.php'));
 
  if ($config->logging->app) {
    $di->getLogger ()->log ("Initialization time: " . (microtime (true) - APP_START_TIME));    
  } 
  
  // Output application result
  echo ($application->handle ()->getContent ());
  
 
  if ($config->logging->app) {
    $di->getLogger ()->log ("Execution time: " . (microtime (true) - APP_START_TIME));    
  }        
 //pinba.flush();
 
                                                                      
  
KeyValue
_url/sitemap/massage
KeyValue
USERapache
HOME/var/www
FCGI_ROLERESPONDER
SCRIPT_FILENAME/var/www/html/public/index.php
QUERY_STRING_url=/sitemap/massage
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_NAME/index.php
REQUEST_URI/sitemap/massage
DOCUMENT_URI/index.php
DOCUMENT_ROOT/var/www/html/public
SERVER_PROTOCOLHTTP/1.0
GATEWAY_INTERFACECGI/1.1
SERVER_SOFTWAREnginx/1.6.2
REMOTE_ADDR54.146.176.30
REMOTE_PORT41351
SERVER_ADDR172.31.17.249
SERVER_PORT80
SERVER_NAMEptmuadmin.ptmu.co.uk
REDIRECT_STATUS200
HTTP_HOSTwww.ptmu.co.uk
HTTP_ACCEPT_ENCODINGx-gzip, gzip, deflate
HTTP_USER_AGENTCCBot/2.0 (http://commoncrawl.org/faq/)
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
PHP_SELF/index.php
REQUEST_TIME_FLOAT1487645523.6015
REQUEST_TIME1487645523
#Path
0/var/www/html/public/index.php
1/var/www/html/ptmu/common/config/config.php
2/var/www/html/ptmu/common/config/loader.php
3/var/www/html/ptmu/common/config/services.php
4/var/www/html/ptmu/common/config/modules.php
5/var/www/html/ptmu/common/config/routes.php
6/var/www/html/ptmu/common/library/Utils/Utils.php
7/var/www/html/ptmu/common/library/Taxonomy/Taxonomy0.php
8/var/www/html/ptmu/common/library/Taxonomy/Taxonomy1.php
9/var/www/html/ptmu/frontend/Module.php
10/var/www/html/ptmu/common/library/Phalcon/Session/Adapter/Memcache.php
11/var/www/html/ptmu/frontend/controllers/SitemapController.php
12/var/www/html/ptmu/frontend/controllers/ControllerBase.php
13/var/www/html/ptmu/common/models/Translations.php
14/var/www/html/ptmu/common/models/CacheableModel.php
15/var/www/html/ptmu/common/library/Phalcon/Logger/Adapter/Dummy.php
16/var/www/html/ptmu/common/library/Auth/Auth.php
17/var/www/html/ptmu/common/models/Taxonomy.php
18/var/www/html/ptmu/common/models/Locations.php
19/var/www/html/ptmu/common/library/Location/Location.php
20/var/www/html/ptmu/common/library/ModelsManager/ModelsManager.php
21/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Memcache.php
22/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Base.php
Memory
Usage4456448