コード例 #1
0
ファイル: Connector.php プロジェクト: neok/mongounit
 /**
  * Retrieves a collection object by name.
  *
  * @param string $name
  * @return \MongoCollection
  */
 public function collection($name)
 {
     if (empty($this->collections[$name])) {
         $this->collections[$name] = new \MongoCollection($this->connection->selectDb($this->dbName), $name);
     }
     return $this->collections[$name];
 }
コード例 #2
0
 /**
  * {@inheritdoc}
  * @see http://docs.phalconphp.com/pl/latest/reference/odm.html
  */
 public function register(DiInterface $di)
 {
     $di->set(self::SERVICE_NAME, function () use($di) {
         $mongoConfig = $di->get('config')->mongo->toArray();
         if (isset($mongoConfig['dsn'])) {
             $hostname = $mongoConfig['dsn'];
             unset($mongoConfig['dsn']);
         } else {
             //obtains hostname
             if (isset($mongoConfig['host'])) {
                 $hostname = 'mongodb://' . $mongoConfig['host'];
             } else {
                 $hostname = 'mongodb://localhost';
             }
             if (isset($mongoConfig['port'])) {
                 $hostname .= ':' . $mongoConfig['port'];
             }
             //removes options that are not allowed in MongoClient constructor
             unset($mongoConfig['host']);
             unset($mongoConfig['port']);
         }
         $dbName = $mongoConfig['dbname'];
         unset($mongoConfig['dbname']);
         $mongo = new \MongoClient($hostname, $mongoConfig);
         return $mongo->selectDb($dbName);
     }, true);
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 public function register(DiInterface $di)
 {
     $di->set(self::SERVICE_NAME, function () use($di) {
         $mongo = new \MongoClient();
         return $mongo->selectDb($di->get('config')->mongo->db);
     }, true);
 }
コード例 #4
0
ファイル: CConnMgr.php プロジェクト: luokizz/spp
 public function getMongo($dsn, $options, $db)
 {
     $key = $dsn . "/" . $db;
     if ($this->mongos[$key] == null) {
         $mongoClient = new \MongoClient($dsn, $options);
         $this->mongos[$key] = $mongoClient->selectDb($db);
     }
     return $this->mongos[$key];
 }
コード例 #5
0
ファイル: Config.php プロジェクト: aciden/generator
 public function setMongoDb($dbName)
 {
     $this->set('mongo', function () {
         $mongo = new \MongoClient("mongodb://localhost");
         return $mongo->selectDb($dbName);
     }, true);
     $this->set('collectionManager', function () {
         return new \Phalcon\Mvc\Collection\Manager();
     }, true);
 }
コード例 #6
0
ファイル: bootstrap.php プロジェクト: vegas-cmf/validation
 public function resolve(\Phalcon\Config $config)
 {
     $di = new \Phalcon\Di\FactoryDefault();
     $di->set('config', $config, true);
     $di->set('mongo', function () use($config) {
         $connectionString = "mongodb://{$config->mongo->host}:{$config->mongo->port}";
         $mongo = new \MongoClient($connectionString);
         return $mongo->selectDb($config->mongo->dbname);
     }, true);
     $di->set('collectionManager', function () {
         return new \Phalcon\Mvc\Collection\Manager();
     }, true);
     \Phalcon\Di::setDefault($di);
 }
コード例 #7
0
ファイル: services.php プロジェクト: Xavier94/mydav
    		'error'   => 'alert alert-error',
    		'success' => 'alert alert-success',
    		'notice'  => 'alert alert-notice',
    		'warning' => 'alert alert-warning'
    	));
    */
    /*
    	return new FlashSession(array(
    		'error'   => 'alert alert-danger',
    		'success' => 'alert alert-success',
    		'notice'  => 'alert alert-info',
    		'warning' => 'alert alert-warning'
    	));
    */
});
/**
 * Register a user component
 */
$di->set('elements', function () {
    return new Elements();
});
/**
 * MongoDB
 */
$di->set('mongo', function () {
    $mongo = new MongoClient();
    return $mongo->selectDb("files");
}, true);
$di->set('collectionManager', function () {
    return new Phalcon\Mvc\Collection\Manager();
}, true);
コード例 #8
0
ファイル: Mongo.php プロジェクト: jubinpatel/horde
 /**
  * Const'r
  *
  * @param array  $params   Must contain:
  *      - connection:  (Horde_Mongo_Client  The Horde_Mongo instance.
  *
  * @return Horde_ActiveSync_State_Sql
  */
 public function __construct(array $params = array())
 {
     parent::__construct($params);
     if (empty($this->_params['connection']) || !$this->_params['connection'] instanceof MongoClient) {
         throw new InvalidArgumentException('Missing or invalid connection parameter.');
     }
     $this->_mongo = $params['connection'];
     $this->_db = $this->_mongo->selectDb(null);
 }
コード例 #9
0
ファイル: index.php プロジェクト: OwLoop/Fresh
        return $session;
    });
    $di->set(MEMCACHE, function () {
        $frontCache = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 86400));
        $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array("host" => "localhost", "port" => "11211", "prefix" => MEMCACHE));
        return $cache;
    });
    $config = (require __DIR__ . "/../apps/common/configs/config.php");
    $di->set(DATABASE, function () use($config) {
        return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->dbs->host, "username" => $config->dbs->username, "password" => $config->dbs->password, "dbname" => $config->dbs->name, 'charset' => $config->dbs->charset));
    });
    $di->set('collectionManager', function () {
        return new Phalcon\Mvc\Collection\Manager();
    }, true);
    $di->set('dbm', function () use($config) {
        if (!$config->dbm->username or !$config->dbm->password) {
            $mongo = new MongoClient('mongodb://' . $config->dbm->host);
        } else {
            $mongo = new MongoClient("mongodb://" . $config->dbm->username . ":" . $config->dbm->password . "@" . $config->dbm->host, array("db" => $config->dbm->name));
        }
        return $mongo->selectDb($config->dbm->name);
    }, TRUE);
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    $application->registerModules(array('frontend' => array('className' => 'Modules\\Frontend\\Module', 'path' => '../apps/frontend/Module.php'), 'backend' => array('className' => 'Modules\\Backend\\Module', 'path' => '../apps/backend/Module.php')));
    echo $application->handle()->getContent();
} catch (Phalcon\Exception $e) {
    echo $e->getMessage();
} catch (PDOException $e) {
    echo $e->getMessage();
}
コード例 #10
0
      <?php 
    foreach ($dbs['databases'] as $db) {
        if ($db['name'] === 'local' || $db['name'] === 'admin') {
            continue;
        }
        ?>
        <tr>
          <td><a href="<?php 
        echo $_SERVER['PHP_SELF'] . '?db=' . urlencode($db['name']);
        ?>
"><?php 
        echo $db['name'];
        ?>
</a></td>
          <td><?php 
        echo count($mongo->selectDb($db['name'])->listCollections());
        ?>
</td>

          <?php 
        if ($readOnly !== true) {
            ?>
            <td><a href="<?php 
            echo $_SERVER['PHP_SELF'];
            ?>
?delete_db=<?php 
            echo urlencode($db['name']);
            ?>
" onClick="return confirm('Are you sure you want to delete this database?');">Delete</a></td>
          <?php 
        } else {
コード例 #11
0
ファイル: PepVN_Cache.php プロジェクト: Bushzhao/rvbwebsite
 public function __construct($options = array())
 {
     $options = array_merge(array('cache_timeout' => 3600, 'hash_key_method' => 'crc32b', 'hash_key_salt' => '', 'gzcompress_level' => 2, 'key_prefix' => ''), (array) $options);
     $checkStatus1 = false;
     if (isset($options['cache_methods']) && $options['cache_methods'] && !empty($options['cache_methods'])) {
         $shortKeysMethodsCache = $this->_shortKeysMethodsCache;
         foreach ($options['cache_methods'] as $key1 => $val1) {
             if (!isset($shortKeysMethodsCache[$key1])) {
                 unset($options['cache_methods'][$key1]);
             }
         }
         if ($options['cache_methods'] && !empty($options['cache_methods'])) {
             $checkStatus1 = true;
         }
     }
     if ($checkStatus1) {
         $options['gzcompress_level'] = (int) $options['gzcompress_level'];
         if ($options['gzcompress_level'] > 9) {
             $options['gzcompress_level'] = 9;
         } elseif ($options['gzcompress_level'] < 0) {
             $options['gzcompress_level'] = 0;
         }
         if (isset($_SERVER['REQUEST_TIME']) && $_SERVER['REQUEST_TIME']) {
             $this->_requestTime = $_SERVER['REQUEST_TIME'];
         } else {
             $this->_requestTime = time();
         }
         $this->_requestTime = (int) $this->_requestTime;
         /*
          * APC
          */
         if (isset($options['cache_methods']['apc'])) {
             if (!function_exists('apc_exists')) {
                 unset($options['cache_methods']['apc']);
             }
         }
         /*
          * Memcache
          */
         if (isset($options['cache_methods']['memcache'])) {
             if (isset($options['cache_methods']['memcache']['object']) && $options['cache_methods']['memcache']['object']) {
                 $this->_memcache = $options['cache_methods']['memcache']['object'];
                 unset($options['cache_methods']['memcache']['object']);
             } else {
                 if (isset($options['cache_methods']['memcache']['servers']) && $options['cache_methods']['memcache']['servers'] && !empty($options['cache_methods']['memcache']['servers'])) {
                     $memcacheType = false;
                     if (class_exists('\\Memcached')) {
                         $memcacheType = 'memcached';
                     } else {
                         if (class_exists('\\Memcache')) {
                             $memcacheType = 'memcache';
                         }
                     }
                     if (false !== $memcacheType) {
                         if ('memcached' === $memcacheType) {
                             $this->_memcache = new \Memcached();
                         } else {
                             if ('memcache' === $memcacheType) {
                                 $this->_memcache = new \Memcache();
                             }
                         }
                         if ($this->_memcache) {
                             foreach ($options['cache_methods']['memcache']['servers'] as $val1) {
                                 if ($val1) {
                                     $opt1 = array_merge(array('host' => '127.0.0.1', 'port' => '11211', 'persistent' => true, 'weight' => 1), $val1);
                                     $addServerStatus = false;
                                     if ('memcached' === $memcacheType) {
                                         $addServerStatus = $this->_memcache->addServer($opt1['host'], $opt1['port'], $opt1['weight']);
                                     } else {
                                         //memcache
                                         $addServerStatus = $this->_memcache->addServer($opt1['host'], $opt1['port'], $opt1['persistent'], $opt1['weight']);
                                     }
                                 }
                             }
                         }
                         $memcacheVersion = false;
                         if ($this->_memcache) {
                             $memcacheVersion = $this->_memcache->getVersion();
                         }
                         if (false === $memcacheVersion) {
                             $this->_memcache = false;
                         } else {
                             $this->_memcacheType = $memcacheType;
                         }
                         unset($options['cache_methods']['memcache']['servers']);
                     }
                 }
             }
         }
         /*
          * Mongo
          */
         if (isset($options['cache_methods']['mongo'])) {
             if (isset($options['cache_methods']['mongo']['object']) && $options['cache_methods']['mongo']['object']) {
                 $this->_mongo = $options['cache_methods']['mongo']['object'];
                 unset($options['cache_methods']['mongo']['object']);
             } else {
                 if (isset($options['cache_methods']['mongo']['servers']) && $options['cache_methods']['mongo']['servers'] && !empty($options['cache_methods']['mongo']['servers'])) {
                     if (isset($options['cache_methods']['mongo']['servers']['host']) && $options['cache_methods']['mongo']['servers']['host'] && isset($options['cache_methods']['mongo']['servers']['db']) && $options['cache_methods']['mongo']['servers']['db'] && isset($options['cache_methods']['mongo']['servers']['collection']) && $options['cache_methods']['mongo']['servers']['collection']) {
                         $mongoClient = new \MongoClient($options['cache_methods']['mongo']['servers']['host']);
                         if ($mongoClient) {
                             $this->_mongo = $mongoClient->selectDb($options['cache_methods']['mongo']['servers']['db'])->selectCollection($options['cache_methods']['mongo']['servers']['collection']);
                         }
                     }
                     unset($options['cache_methods']['mongo']['servers']);
                 }
             }
         }
         /*
          * File
          */
         if (isset($options['cache_methods']['file'])) {
             $isCacheMethodFileValid = false;
             if (isset($options['cache_methods']['file']['cache_dir'])) {
                 if ($options['cache_methods']['file']['cache_dir']) {
                     if (!file_exists($options['cache_methods']['file']['cache_dir']) || !is_dir($options['cache_methods']['file']['cache_dir'])) {
                         @mkdir($options['cache_methods']['file']['cache_dir'], 0755, true);
                     }
                     if (file_exists($options['cache_methods']['file']['cache_dir']) && is_dir($options['cache_methods']['file']['cache_dir'])) {
                         if (is_readable($options['cache_methods']['file']['cache_dir']) && is_writable($options['cache_methods']['file']['cache_dir'])) {
                             $isCacheMethodFileValid = true;
                         }
                     }
                 }
             }
             if (!$isCacheMethodFileValid) {
                 unset($options['cache_methods']['file']);
             }
         }
         if ($options['cache_methods'] && !empty($options['cache_methods'])) {
             $this->_options = $options;
         }
     }
     $options = null;
     unset($options);
     if (function_exists('igbinary_serialize')) {
         $this->_has_igbinary = true;
     }
     $this->_key_salt = '_' . substr(hash('crc32b', $this->_serialize($this->_options)), 0, 2) . '_';
 }
コード例 #12
0
// load classes
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Application;
// initialize Silex application
$app = new Application();
// load configuration from file
$app->config = $config;
// register Twig template provider
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
// register URL generator
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
// configure MongoDB client
$dbn = substr(parse_url($app->config['db_uri'], PHP_URL_PATH), 1);
$mongo = new MongoClient($app->config['db_uri'], array("connectTimeoutMS" => 30000));
$db = $mongo->selectDb($dbn);
// if BlueMix VCAP_SERVICES environment available
// overwrite with credentials from BlueMix
if ($services = getenv("VCAP_SERVICES")) {
    $services_json = json_decode($services, true);
    $app->config['weather_uri'] = $services_json["weatherinsights"][0]["credentials"]["url"];
}
// index page handlers
$app->get('/', function () use($app) {
    return $app->redirect($app["url_generator"]->generate('index'));
});
$app->get('/index', function () use($app, $db) {
    // get list of locations from database
    // for each location, get current weather from Weather service
    $collection = $db->locations;
    $locations = iterator_to_array($collection->find());
コード例 #13
0
ファイル: cli.php プロジェクト: OwLoop/Fresh
$di->set('crm', function () use($config) {
    return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->crm->host, "username" => $config->crm->username, "password" => $config->crm->password, "dbname" => $config->crm->name, 'charset' => $config->crm->charset));
});
$di->set('ads', function () use($config) {
    return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->ads->host, "username" => $config->ads->username, "password" => $config->ads->password, "dbname" => $config->ads->name));
});
$di->set('collectionManager', function () {
    return new Phalcon\Mvc\Collection\Manager();
}, true);
$di->set('bigdata', function () use($config) {
    if (!$config->bigdata->username or !$config->bigdata->password) {
        $mongo = new MongoClient('mongodb://' . $config->bigdata->host);
    } else {
        $mongo = new MongoClient("mongodb://" . $config->bigdata->username . ":" . $config->bigdata->password . "@" . $config->bigdata->host, array("db" => $config->bigdata->name));
    }
    return $mongo->selectDb($config->bigdata->name);
}, TRUE);
$di->set('crmcache', function () {
    // Cache data for one day by default
    $frontCache = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 86400));
    // Memcached connection settings
    $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array("host" => "221.133.7.87", "port" => "11211", "prefix" => PREFIX_CACHE));
    return $cache;
});
$di->set('crmcacheap', function () {
    // Cache data for one day by default
    $frontCache = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 86400));
    // Memcached connection settings
    $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array("host" => "221.133.7.87", "port" => "11211", "prefix" => 'crmcacheap'));
    return $cache;
});
コード例 #14
0
ファイル: load.php プロジェクト: husseinsharif/crcl
<?php

/* Standard options */
$uri = "mongodb://*****:*****@ds041581.mongolab.com:41581/echo";
$options = array("connectTimeoutMS" => 30000);
/* Create Mongo connection with URI and options*/
$client = new MongoClient($uri, $options);
/* Reference the proper database */
$db = $client->selectDb("echo");
/* Reference the proper collection */
$reports = $db->selectCollection("reports");
// Find all markers
$cursor = $reports->find();
$allMarkers = array();
foreach ($cursor as $value) {
    array_push($allMarkers, $value);
}
// Close DB
$client->close();
// Send stringified json back to Javascript
// header('Content-Type: application/json');
echo json_encode($allMarkers);
コード例 #15
0
ファイル: services.php プロジェクト: ensaier/vvkp.in.ua
 */
$di->set('modelsMetadata', function () {
    return new MetaData();
});
/**
 * Start the session the first time some component request the session service
 */
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
/**
 * Register the flash service with custom CSS classes
 */
$di->set('flash', function () {
    return new FlashSession(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
});
/**
 * Register a user component
 */
$di->set('elements', function () {
    return new Elements();
});
$di->set('mongo', function () {
    $mongo = new MongoClient();
    return $mongo->selectDb("pidors");
}, true);
$di->set('collectionManager', function () {
    return new Phalcon\Mvc\Collection\Manager();
}, true);
コード例 #16
0
ファイル: index.php プロジェクト: atduarte/allsos
<?php

ini_set("display_errors", 1);
error_reporting(E_ALL);
try {
    //Register an autoloader
    $loader = new \Phalcon\Loader();
    $loader->registerNamespaces(['AllSOS\\Controllers' => __DIR__ . '/../app/controllers/', 'AllSOS\\Models' => __DIR__ . '/../app/models/']);
    $loader->register();
    //Create a DI
    $di = new \Phalcon\DI\FactoryDefault();
    //Setting MongoDB
    $di->set('mongo', function () {
        $mongo = new MongoClient();
        return $mongo->selectDb("allsos");
    }, true);
    //Registering the collectionManager service
    $di->set('collectionManager', function () {
        return new Phalcon\Mvc\Collection\Manager();
    }, true);
    //Setting Router
    $di->set('router', function () {
        return require __DIR__ . '/../app/config/routes.php';
    });
    //Setting URL Helper
    $di->set('url', function () {
        $url = new Phalcon\Mvc\Url();
        return $url;
    });
    //Registering the view component
    $di->set('view', function () {
コード例 #17
0
ファイル: cli-crawler.php プロジェクト: mysmartcity/flux
                }
            }
        }
    }
}
function encodingCleanup($sString)
{
    $sString = json_encode($sString);
    $sString = substr($sString, 1);
    $sString = substr($sString, 0, -1);
    return $sString;
}
/* main { */
$oMongo = new MongoClient();
// connect
$oDb = $oMongo->selectDb("flux");
//DEBUG: init the collections {
if (true == false) {
    //SET TO FALSE DURING PRODUCTION OTHERWISE THE COLLECTIONS WILL BE INITIALIZED
    $oDb->pages->drop();
    $oDb->news->drop();
    $oDb->sources->drop();
    $oDb->sources->insert([['category' => 'transport', 'sources' => ['http://www.mt.ro/', 'http://www.cfr.ro/']], ['category' => 'health', 'sources' => ['http://www.ms.ro/']], ['category' => 'youth', 'sources' => ['http://www.mts.ro/']]]);
}
//} DEBUG
$oCursor = $oDb->sources->find();
if ($oCursor) {
    foreach ($oCursor as $aCategories) {
        foreach ($aCategories as $aCategory) {
            if (is_array($aCategory)) {
                $sCategory = $aCategory['category'];
コード例 #18
0
ファイル: Module2.php プロジェクト: b2bpolis/kladrapi
 /**
  * Регистрация сервисов модуля
  */
 public function registerServices(\Phalcon\DiInterface $di)
 {
     $config = new \Phalcon\Config\Adapter\Ini(__DIR__ . '/config/config.ini');
     // Set site config
     $di->set('config', $config);
     // Setting up mongo
     $di->set('mongo', function () use($config) {
         $mongo = new \MongoClient($config->database->host);
         return $mongo->selectDb($config->database->name);
     }, true);
     // Registering the collectionManager service
     $di->set('collectionManager', function () {
         $modelsManager = new \Phalcon\Mvc\Collection\Manager();
         return $modelsManager;
     }, true);
     // Start the session the first time when some component request the session service
     $di->set('session', function () use($config) {
         if (isset($config->session->adapter)) {
             switch ($config->session->adapter) {
                 case 'mongo':
                     $mongo = new \Mongo($config->session->mongoHost);
                     $session = new \Phalcon\Session\Adapter\Mongo(array('collection' => $mongo->kladrapiSession->data));
                     break;
                 case 'file':
                     $session = new \Phalcon\Session\Adapter\Files();
                     break;
             }
         } else {
             $session = new \Phalcon\Session\Adapter\Files();
         }
         $session->start();
         return $session;
     });
     // Setting up dispatcher
     $di->set('dispatcher', function () use($di) {
         $evManager = $di->getShared('eventsManager');
         $evManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
             switch ($exception->getCode()) {
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                     $dispatcher->forward(array('controller' => 'index', 'action' => 'show404'));
                     return false;
             }
         });
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $dispatcher->setDefaultNamespace("Kladr\\Frontend\\Controllers");
         $dispatcher->setEventsManager($evManager);
         return $dispatcher;
     });
     // Register an user component
     $di->set('elements', function () {
         return new Library\Elements();
     });
     // Register key tools
     $di->set('keyTools', function () {
         return new Plugins\KeyTools();
     });
     // Register the flash service with custom CSS classes
     $di->set('flash', function () {
         $flash = new \Phalcon\Flash\Direct();
         return $flash;
     });
     // Setting up the view component
     $di->set('view', function () {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../apps/frontend/views/');
         return $view;
     });
 }
コード例 #19
0
ファイル: Module.php プロジェクト: sarahsampan/compare-api
 /**
  * Mount the module specific routes before the module is loaded.
  * Add ModuleRoutes Group and annotated controllers for parsing their routing information.
  *
  * @param \Phalcon\DiInterface  $di
  */
 public static function initRoutes(DiInterface $di)
 {
     $loader = new Loader();
     $loader->registerNamespaces(['App\\Modules\\Backend\\Controllers' => __DIR__ . '/Controllers/', 'App\\Modules\\Backend\\Controllers\\API' => __DIR__ . '/Controllers/api/', 'App\\Modules\\Backend\\Models' => __DIR__ . '/Models/', 'App\\Modules\\Backend\\Library' => __DIR__ . '/Lib/', 'App\\Modules\\Frontend\\Controllers' => __DIR__ . '/../Frontend/Controllers/', 'App\\Modules\\Frontend\\Models' => __DIR__ . '/../Frontend/Models/'], TRUE)->register();
     /**
      * Read application wide and module only configurations
      */
     $appConfig = $di->get('config');
     $moduleConfig = (include __DIR__ . '/config/config.php');
     $di->setShared('moduleConfig', $moduleConfig);
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->setShared('url', function () use($appConfig) {
         $url = new UrlResolver();
         $url->setBaseUri($appConfig->application->baseUri);
         return $url;
     });
     $di->setShared('request', function () use($appConfig) {
         return new \Phalcon\Http\Request();
     });
     /**
      * Read configuration
      */
     include __DIR__ . "/../../config/env/" . $appConfig->application->environment . ".php";
     $database = $di->getConfig()->application->site . $di->get('request')->getQuery("countryCode");
     /**
      * Module specific database connection
      */
     $di->set('db', function () use($config, $database) {
         $eventsManager = new \Phalcon\Events\Manager();
         //Create a database listener
         $dbListener = new MyDBListener();
         //Listen all the database events
         $eventsManager->attach('db', $dbListener);
         $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => $config->{$database}->host, 'username' => $config->{$database}->username, 'password' => $config->{$database}->password, 'dbname' => $config->{$database}->dbname, 'options' => array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'")]);
         //Assign the eventsManager to the db adapter instance
         $connection->setEventsManager($eventsManager);
         return $connection;
     });
     /**
      * Simple database connection to localhost
      */
     $di->set('mongo', function () use($config, $database) {
         $mongo = new \MongoClient();
         return $mongo->selectDb($config->{$database}->dbname);
     }, true);
     $di->set('collectionManager', function () {
         return new \Phalcon\Mvc\Collection\Manager();
     }, true);
     /**
      * Include composer autoloader
      */
     require __DIR__ . "/../../../vendor/autoload.php";
     /**
      * Module specific dispatcher
      */
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace('App\\Modules\\Backend\\Controllers\\');
         return $dispatcher;
     });
     $di->set('utils', function () {
         require __DIR__ . "/../../Common/Lib/Application/Plugins/Utils.php";
         $utils = new Utils();
         return $utils;
     });
     /**
      * If our request contains a body, it has to be valid JSON.  This parses the
      * body into a standard Object and makes that available from the DI.  If this service
      * is called from a function, and the request body is not valid JSON or is empty,
      * the program will throw an Exception.
      */
     $di->setShared('requestBody', function () {
         parse_str(file_get_contents("php://input"), $in);
         // JSON body could not be parsed, throw exception
         if ($in === null) {
             throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => ''));
         }
         return $in;
     });
     /**
      * This means we can create listeners that run when an event is triggered.
      */
     $di->setShared('modelsManager', function () use($di, $config, $database) {
         $eventsManager = new \Phalcon\Events\Manager();
         $customModelsManager = new CustomModelsManager();
         /**
          * Attach an anonymous function as a listener for "model" events
          */
         $eventsManager->attach('model', $customModelsManager);
         /**
          * Setting a default EventsManager
          */
         $customModelsManager->setEventsManager($eventsManager);
         return $customModelsManager;
     });
 }
コード例 #20
0
ファイル: Module2.php プロジェクト: b2bpolis/kladrapi
 /**
  * Регистрация сервисов модуля
  */
 public function registerServices(\Phalcon\DiInterface $di)
 {
     $config = new \Phalcon\Config\Adapter\Ini(__DIR__ . '/config/config.ini');
     // Set site config
     $di->set('config', $config);
     // Setting up mongo
     $di->set('mongo', function () use($config) {
         $mongo = new \MongoClient($config->database->host, array('connectTimeoutMS' => intval($config->database->timeout)));
         return $mongo->selectDb($config->database->name);
     }, true);
     // Mongo with users
     $di->set('mongoUsers', function () use($config) {
         $mongo = new \MongoClient($config->database->usersHost, array('connectTimeoutMS' => intval($config->database->timeout)));
         return $mongo->selectDb($config->database->usersName);
     }, true);
     // Mongo with users
     $di->set('mongoLog', function () use($config) {
         $mongo = new \MongoClient($config->database->logHost, array('connectTimeoutMS' => intval($config->database->timeout)));
         return $mongo->selectDb($config->database->logName);
     }, true);
     // Service for running users
     $di->set('userService', '\\Kladr\\Core\\Services\\UserService');
     // Registering the collectionManager service
     $di->set('collectionManager', function () {
         $modelsManager = new \Phalcon\Mvc\Collection\Manager();
         return $modelsManager;
     }, true);
     // Setting up dispatcher
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $dispatcher->setDefaultNamespace('Kladr\\Core\\Controllers');
         return $dispatcher;
     });
     // Setting memcache
     $di->set('memcache', function () use($config) {
         $frontCache = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 86400));
         $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array("host" => $config->memcache->host, "port" => $config->memcache->port));
         return $cache;
     });
     // Settings mongocache
     $di->set('mongocache', function () use($config) {
         $frontCache = new \Phalcon\Cache\Frontend\Data(array("lifetime" => 86400));
         $cache = new \Phalcon\Cache\Backend\Mongo($frontCache, array('server' => 'mongodb://' . $config->mongocache->host, 'db' => $config->mongocache->db, 'collection' => $config->mongocache->collection, 'connectTimeoutMS' => intval($config->mongocache->timeout)));
         return $cache;
     });
     // Setting cache
     $di->set('cache', array('className' => '\\Kladr\\Core\\Plugins\\Tools\\Cache', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'mongocache')), array('name' => 'config', 'value' => array('type' => 'service', 'name' => 'config')))));
     //setting sphinxapi
     $di->set('sphinxapi', function () use($config) {
         include dirname(__FILE__) . '/plugins/tools/sphinxapi.php';
         $sphinxapi = new \SphinxClient();
         $sphinxapi->SetServer($config->sphinxapi->server, $config->sphinxapi->port);
         return $sphinxapi;
     });
     // Register validate plugin
     $di->set('validate', function () {
         return new \Kladr\Core\Plugins\General\ValidatePlugin();
     });
     // Register oneString plugin
     $di->set('oneString', array('className' => '\\Kladr\\Core\\Plugins\\General\\OneStringPlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')), array('name' => 'sphinxClient', 'value' => array('type' => 'service', 'name' => 'sphinxapi')))));
     // Register find plugin
     $di->set('find', array('className' => '\\Kladr\\Core\\Plugins\\General\\FindPlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')))));
     // Register special cases plugin
     $di->set('specialCases', array('className' => '\\Kladr\\Core\\Plugins\\General\\SpecialCasesPlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')))));
     // Register duplicate plugin
     $di->set('duplicate', array('className' => '\\Kladr\\Core\\Plugins\\General\\DuplicatePlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')))));
     // Register find parents plugin
     $di->set('findParents', array('className' => '\\Kladr\\Core\\Plugins\\General\\FindParentsPlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')))));
     // Register find parents plugin
     $di->set('parentsSpecialCases', array('className' => '\\Kladr\\Core\\Plugins\\General\\ParentsSpecialCasesPlugin', 'properties' => array(array('name' => 'cache', 'value' => array('type' => 'service', 'name' => 'cache')))));
     // Register find parents plugin
     $di->set('logPaidUsersPlugin', array('className' => '\\Kladr\\Core\\Plugins\\General\\LogPaidUsersPlugin', 'properties' => array(array('name' => 'userService', 'value' => array('type' => 'service', 'name' => 'userService')))));
     $di->set('allDataPlugin', array('className' => '\\Kladr\\Core\\Plugins\\General\\AllDataPlugin', 'properties' => array(array('name' => 'userService', 'value' => array('type' => 'service', 'name' => 'userService')), array('name' => 'cacheDir', 'value' => array('type' => 'parameter', 'value' => $config->application->cacheDir)), array('name' => 'disablePaid', 'value' => array('type' => 'parameter', 'value' => $config->application->disablePaid)))));
     $di->set('enabledTokensPlugin', '\\Kladr\\Core\\Plugins\\General\\EnabledTokensPlugin');
     // Register GA
     $di->set('apiTracker', function () use($config) {
         if ($config->ga->code == '') {
             return false;
         }
         return new \Racecore\GATracking\GATracking($config->ga->code);
     });
     // Setting api
     $di->setShared('api', function () use($di, $config) {
         $api = new Services\ApiService($di->get('apiTracker'));
         if ($config->application->enableTokens) {
             $api->addPlugin($di->get('enabledTokensPlugin'));
         }
         if ($config->application->enableUserLog) {
             $api->addPlugin($di->get('logPaidUsersPlugin'));
         }
         $api->addPlugin($di->get('allDataPlugin'));
         $api->addPlugin($di->get('validate'));
         if ($config->sphinxapi->enabled) {
             $api->addPlugin($di->get('oneString'));
         }
         $api->addPlugin($di->get('find'));
         //$api->addPlugin($di->get('specialCases'));
         //$api->addPlugin($di->get('duplicate'));
         $api->addPlugin($di->get('findParents'));
         $api->addPlugin($di->get('parentsSpecialCases'));
         return $api;
     });
     // Setting up the view component
     $di->set('view', function () use($config) {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir($config->application->viewsDir);
         return $view;
     });
 }
コード例 #21
0
ファイル: bootstrap.php プロジェクト: vegas-cmf/media
define('APP_ROOT', TESTS_ROOT_DIR . '/fixtures');
$configArray = (require_once TESTS_ROOT_DIR . '/config.php');
$_SERVER['HTTP_HOST'] = 'vegas.dev';
$_SERVER['REQUEST_URI'] = '/';
$config = new \Phalcon\Config($configArray);
$di = new Phalcon\DI\FactoryDefault();
$di->set('config', $config);
$di->set('collectionManager', function () use($di) {
    return new \Phalcon\Mvc\Collection\Manager();
}, true);
$di->set('collectionManager', function () {
    return new \Phalcon\Mvc\Collection\Manager();
});
$view = new \Phalcon\Mvc\View();
$view->registerEngines(array('.volt' => function ($this, $di) {
    $volt = new \Phalcon\Mvc\View\Engine\Volt($this, $di);
    $volt->setOptions(array('compiledPath' => TESTS_ROOT_DIR . '/fixtures/cache/', 'compiledSeparator' => '_'));
    return $volt;
}, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
$di->set('view', $view);
$di->set('mongo', function () use($config) {
    $mongo = new \MongoClient();
    return $mongo->selectDb($config->mongo->db);
}, true);
$di->set('modelManager', function () use($di) {
    return new \Phalcon\Mvc\Model\Manager();
}, true);
$di->set('db', function () use($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->toArray());
}, true);
Phalcon\DI::setDefault($di);
コード例 #22
0
ファイル: index.php プロジェクト: atduarte/dailynews-proto
 //Register an autoloader
 $loader = new \Phalcon\Loader();
 // Twig
 require_once __DIR__ . '/../vendor/autoload.php';
 $loader->registerNamespaces(['Notnull\\DailyNews\\Controllers' => __DIR__ . '/../app/controllers/', 'Notnull\\DailyNews\\Models' => __DIR__ . '/../app/models/', 'Notnull\\DailyNews\\Tasks' => __DIR__ . '/../app/tasks/']);
 $loader->register();
 //Create a DI
 if (PHP_SAPI != 'cli') {
     $di = new \Phalcon\DI\FactoryDefault();
 } else {
     $di = new \Phalcon\DI\FactoryDefault\CLI();
 }
 //Setting MongoDB
 $di->set('mongo', function () {
     $mongo = new MongoClient();
     return $mongo->selectDb("ppro");
 }, true);
 //Registering the collectionManager service
 $di->set('collectionManager', function () {
     return new Phalcon\Mvc\Collection\Manager();
 }, true);
 //Setting Router
 if (PHP_SAPI == 'cli') {
     $di->set('dispatcher', function () {
         $dispatcher = new Phalcon\CLI\Dispatcher();
         $dispatcher->setDefaultNamespace('Notnull\\DailyNews\\Tasks');
         return $dispatcher;
     });
 }
 //Setting Router
 if (PHP_SAPI != 'cli') {