コード例 #1
0
 public function createService(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
 {
     $redis = new \Redis();
     $redis->connect('10.0.0.2', 6379);
     //$config = $serviceLocator->get('Configuration');
     $redisCache = new \Doctrine\Common\Cache\RedisCache();
     $redisCache->setRedis($redis);
     return $redis;
 }
コード例 #2
0
 /**
  * @param string $host
  * @param int $port
  * @throws BadMethodCallException
  *
  * @return \Doctrine\Common\Cache\RedisCache
  */
 private static function configureRedisCache($host = '127.0.0.1', $port = 6379)
 {
     if (!extension_loaded('redis')) {
         throw new \BadMethodCallException('RedisCache configured but module \'redis\' not loaded.');
     }
     $redis = new \Redis();
     $redis->connect($host, $port);
     $cache = new \Doctrine\Common\Cache\RedisCache();
     $cache->setRedis($redis);
     return $cache;
 }
コード例 #3
0
ファイル: RedisCache.php プロジェクト: kohana/doctrine
 /**
  * @param array $cacheConfig
  * @return \Doctrine\Common\Cache\MemcacheCache
  * @throws IncorrectConfigurationException
  */
 public function configureCache(array $cacheConfig)
 {
     if (empty($cacheConfig['host'])) {
         throw new IncorrectConfigurationException('cache.memcache.host');
     }
     if (empty($cacheConfig['port'])) {
         throw new IncorrectConfigurationException('cache.memcache.port');
     }
     if (empty($cacheConfig['timeout'])) {
         $cacheConfig['timeout'] = 0.0;
     }
     $redis = $this->configureRedis($cacheConfig['host'], $cacheConfig['port'], $cacheConfig['timeout']);
     $cacheDriver = new \Doctrine\Common\Cache\RedisCache();
     $cacheDriver->setRedis($redis);
     return $cacheDriver;
 }
コード例 #4
0
 /**
  * Get cache driver according to config.yml entry.
  *
  * Logic from Doctrine setup method
  * https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Setup.php#L122
  *
  * @param  array      $cacheConfig
  * @param  boolean    $isDevMode
  * @param  string|null $proxyDir
  * @return Cache
  */
 protected function getManuallyDefinedCache(array $cacheConfig, $isDevMode = false, $proxyDir = null)
 {
     $proxyDir = $proxyDir ?: sys_get_temp_dir();
     if ($isDevMode === false) {
         if (extension_loaded('apc') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'apc') {
             $cache = new \Doctrine\Common\Cache\ApcCache();
         } elseif (extension_loaded('xcache') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'xcache') {
             $cache = new \Doctrine\Common\Cache\XcacheCache();
         } elseif (extension_loaded('memcache') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'memcache') {
             $memcache = new \Memcache();
             $host = !empty($cacheConfig['host']) ? $cacheConfig['host'] : '127.0.0.1';
             if (!empty($cacheConfig['port'])) {
                 $memcache->connect($host, $cacheConfig['port']);
             } else {
                 $memcache->connect($host);
             }
             $cache = new \Doctrine\Common\Cache\MemcacheCache();
             $cache->setMemcache($memcache);
         } elseif (extension_loaded('redis') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'redis') {
             $redis = new \Redis();
             $host = !empty($cacheConfig['host']) ? $cacheConfig['host'] : '127.0.0.1';
             if (!empty($cacheConfig['port'])) {
                 $redis->connect($host, $cacheConfig['port']);
             } else {
                 $redis->connect($host);
             }
             $cache = new \Doctrine\Common\Cache\RedisCache();
             $cache->setRedis($redis);
         } else {
             $cache = new ArrayCache();
         }
     } else {
         $cache = new ArrayCache();
     }
     if ($cache instanceof CacheProvider) {
         $cache->setNamespace("dc2_" . md5($proxyDir) . "_");
         // to avoid collisions
     }
     return $cache;
 }
コード例 #5
0
ファイル: di.php プロジェクト: nitheeshp/bookshelf
    $loader = new Twig_Loader_Filesystem([$twigBridgeViews, './app/Resources/view']);
    $twig = new Twig_Environment($loader, $c->get('parameters')['twig']['loader_options']);
    $twig->addGlobal('show_exception_backtrace', $c->get('parameters')['twig']['show_exception_backtrace']);
    $twig->addGlobal('session', $c->get('session'));
    $formEngine = new \Symfony\Bridge\Twig\Form\TwigRendererEngine(['bootstrap_3_layout.html.twig']);
    $formEngine->setEnvironment($twig);
    $formExt = new \Symfony\Bridge\Twig\Extension\FormExtension(new \Symfony\Bridge\Twig\Form\TwigRenderer($formEngine));
    $twig->addExtension($formExt);
    $transExt = new \Symfony\Bridge\Twig\Extension\TranslationExtension($c->get('translator'));
    $twig->addExtension($transExt);
    return $twig;
}), 'router' => function () {
    return \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
        $r->addRoute('GET', '/', ['ClassicApp\\Controller\\IndexController', 'index']);
        $r->addRoute('GET', '/book', ['ClassicApp\\Controller\\BookController', 'index']);
        $r->addRoute('GET', '/book/new', ['ClassicApp\\Controller\\BookController', 'create']);
        $r->addRoute('POST', '/book/new', ['ClassicApp\\Controller\\BookController', 'create']);
    });
}, 'redis' => \DI\factory(function (\DI\Container $c) {
    $redis = new Redis();
    $redis->connect($c->get('parameters')['redis']['host'], $c->get('parameters')['redis']['port']);
    return $redis;
}), 'doctrine.dbal' => \DI\factory(function (\DI\Container $c) {
    return Doctrine\DBAL\DriverManager::getConnection($c->get('parameters')['doctrine']['conn']);
}), 'doctrine.em' => \DI\factory(function (\DI\Container $c) {
    $cacheDriver = new \Doctrine\Common\Cache\RedisCache();
    $cacheDriver->setRedis($c->get('redis'));
    $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($c->get('parameters')['doctrine']['orm']['entityPaths'], $c->get('parameters')['doctrine']['orm']['devMode'], $c->get('parameters')['doctrine']['orm']['proxyDir'], $cacheDriver, false);
    $dbal = $c->get('doctrine.dbal');
    return \Doctrine\ORM\EntityManager::create($dbal, $config);
})];
コード例 #6
0
ファイル: Aplicativo.php プロジェクト: netinhoteixeira/pudim
 /**
  * Tenta estabelecer a conexão ao banco relacional ou de documentos.
  * 
  * @return \Doctrine\ORM\EntityManager | \Doctrine\ODM\MongoDB\DocumentManager
  */
 private function estabelecerConexao()
 {
     $tipo = explode(':', $this->_configuracao->get($this->_servidor . '.persistencia_uri'));
     $tipo = $tipo[0];
     if (!empty($tipo)) {
         if ($tipo === 'mongodb') {
             \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver::registerAnnotationClasses();
         }
         $classLoader = new ClassLoader('Domain\\Entity', implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']));
         $classLoader->register();
         $doctrine_models_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']);
         $doctrine_entities_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models', 'Domain', 'Entity']);
         $doctrine_proxies_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Proxies']);
         $doctrine_hydrators_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Hydrators']);
         // cria os diretórios dos proxys e hydrators, caso não haja (necessários
         // para o Doctrine)
         if (!PROJECT_STAGE) {
             Arquivo::criarDiretorio($doctrine_proxies_dir);
             Arquivo::criarDiretorio($doctrine_hydrators_dir);
         }
         // verifica se não é MongoDB
         if ($tipo !== 'mongodb') {
             // provê algumas informações iniciais do banco de dados
             switch ($tipo) {
                 case 'sqlite':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'path' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
                 case 'mysql':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco'), \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET CHARACTER SET \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_connection=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_client=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_results=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\';'];
                     break;
                     // em teste funciona para quase todos os tipos de PDO
                 // em teste funciona para quase todos os tipos de PDO
                 default:
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
             }
             // cria os mapeamentos das entidades do banco de dados, caso não existam
             if (count(glob($doctrine_entities_dir . '/*.php')) === 0) {
                 $configuracao = new \Doctrine\ORM\Configuration();
                 $configuracao->setMetadataDriverImpl($configuracao->newDefaultAnnotationDriver($doctrine_entities_dir, FALSE));
                 $configuracao->setProxyDir($doctrine_proxies_dir);
                 $configuracao->setProxyNamespace('Proxies');
                 $entityManager = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao);
                 // custom datatypes (not mapped for reverse engineering)
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
                 // define namespace
                 $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($entityManager->getConnection()->getSchemaManager());
                 $driver->setNamespace('Domain\\Entity\\');
                 // define driver with namespace
                 $entityManager->getConfiguration()->setMetadataDriverImpl($driver);
                 $disconnectedClassMetadataFactory = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
                 $disconnectedClassMetadataFactory->setEntityManager($entityManager);
                 $entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
                 $entityGenerator->setUpdateEntityIfExists(true);
                 $entityGenerator->setGenerateStubMethods(true);
                 $entityGenerator->setGenerateAnnotations(true);
                 $entityGenerator->generate($disconnectedClassMetadataFactory->getAllMetadata(), $doctrine_models_dir);
             }
             // carrega as entidades
             \Pudim\Arquivo::requererDiretorio($doctrine_entities_dir);
             $configuracao = \Doctrine\ORM\Tools\Setup::createConfiguration(!(bool) PROJECT_STAGE);
             $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(new \Doctrine\Common\Annotations\AnnotationReader(), $doctrine_entities_dir);
             // registering noop annotation autoloader - allow all annotations by default
             \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
             $configuracao->setMetadataDriverImpl($driver);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             if (PROJECT_STAGE) {
                 $cache = new \Doctrine\Common\Cache\ArrayCache();
             } else {
                 $cache = new \Doctrine\Common\Cache\ApcCache();
             }
             $configuracao->setMetadataCacheImpl($cache);
             $configuracao->setQueryCacheImpl($cache);
             // obtaining the entity manager (7)
             $eventManager = new \Doctrine\Common\EventManager();
             $conexao = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao, $eventManager);
         } else {
             $configuracao = new \Doctrine\ODM\MongoDB\Configuration();
             $metadata = AnnotationDriver::create($doctrine_entities_dir);
             $configuracao->setMetadataDriverImpl($metadata);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             $configuracao->setAutoGenerateHydratorClasses(!(bool) PROJECT_STAGE);
             $configuracao->setHydratorDir($doctrine_hydrators_dir);
             $configuracao->setHydratorNamespace('Hydrators');
             $configuracao->setDefaultDB($this->_configuracao->get($this->_servidor . '.persistencia_banco'));
             //$configuracao->setLoggerCallable(function (array $log) { print_r($log); });
             $cache_uri = $this->_configuracao->get($this->_servidor . '.cache_uri');
             if (PROJECT_STAGE && class_exists('Redis') && $cache_uri) {
                 // trata o $cache_uri pois somente precisamos do servidor e a porta
                 if (strpos($cache_uri, '//')) {
                     $cache_uri_parts = explode('//', $cache_uri);
                     if (strpos($cache_uri_parts[1], ':')) {
                         list($cache_server, $cache_port) = explode(':', $cache_uri_parts[1]);
                     } else {
                         $cache_server = $cache_uri_parts[1];
                         $cache_port = '6379';
                     }
                     unset($cache_uri_parts);
                 } else {
                     $cache_server = $cache_uri;
                     $cache_port = '6379';
                 }
                 $redis = new \Redis();
                 $redis->pconnect($cache_server, $cache_port);
                 $metadataCache = new \Doctrine\Common\Cache\RedisCache();
                 $metadataCache->setRedis($redis);
                 $configuracao->setMetadataCacheImpl($metadataCache);
                 unset($cache_server, $cache_port, $redis, $metadataCache);
             }
             $conexao = new \Doctrine\MongoDB\Connection($this->_configuracao->get($this->_servidor . '.persistencia_uri'));
             $conexao = \Doctrine\ODM\MongoDB\DocumentManager::create($conexao, $configuracao);
             // FIX: Muito importante pois força a criação dos índices no aplicativo
             $conexao->getSchemaManager()->ensureIndexes();
         }
     }
     return $conexao;
 }
コード例 #7
0
ファイル: handler.php プロジェクト: tokenly/bitcoin-p2p-php
<?php

require_once "../vendor/autoload.php";
$math = BitWasp\Bitcoin\Bitcoin::getMath();
$loop = React\EventLoop\Factory::create();
$factory = new \BitWasp\Bitcoin\Networking\Factory($loop);
$dns = $factory->getDns();
$peerFactory = $factory->getPeerFactory($dns);
$locator = $peerFactory->getLocator();
$handler = $peerFactory->getPacketHandler();
$redis = new Redis();
$redis->connect('127.0.0.1');
$mkCache = function ($namespace) use($redis) {
    $cache = new \Doctrine\Common\Cache\RedisCache();
    $cache->setRedis($redis);
    $cache->setNamespace($namespace);
    return $cache;
};
$headerFS = $mkCache('headers');
$heightFS = $mkCache('height');
$hashFS = $mkCache('hash');
$peerRecorderFS = $mkCache('peer.recorder');
$headerchain = new \BitWasp\Bitcoin\Chain\Headerchain($math, new \BitWasp\Bitcoin\Block\BlockHeader('1', '0000000000000000000000000000000000000000000000000000000000000000', '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', 1231006505, \BitWasp\Buffertools\Buffer::hex('1d00ffff'), 2083236893), new \BitWasp\Bitcoin\Chain\HeaderStorage($headerFS), new \BitWasp\Bitcoin\Chain\BlockIndex(new \BitWasp\Bitcoin\Chain\BlockHashIndex($hashFS), new \BitWasp\Bitcoin\Chain\BlockHeightIndex($heightFS)));
$headerService = new \BitWasp\Bitcoin\Networking\Peer\Services\HeaderIndexService($headerchain);
$pingService = new \BitWasp\Bitcoin\Networking\Peer\Services\PingService($loop);
$debugService = new \BitWasp\Bitcoin\Networking\Peer\Services\DebugPacketService();
$handler->addServices([$pingService, $debugService, $headerService]);
$manager = $peerFactory->getManager($locator, $handler);
$local = $peerFactory->getAddress('192.168.192.39', 32391);
$node = new \BitWasp\Bitcoin\Networking\Node\Node($local, $manager);
$node->start(2);
コード例 #8
0
 private static function getRedisObject()
 {
     if (!defined('__CA_REDIS_HOST__')) {
         define('__CA_REDIS_HOST__', 'localhost');
     }
     if (!defined('__CA_REDIS_PORT__')) {
         define('__CA_REDIS_PORT__', 6379);
     }
     $o_redis = new Redis();
     $o_redis->connect(__CA_REDIS_HOST__, __CA_REDIS_PORT__);
     $o_cache = new \Doctrine\Common\Cache\RedisCache();
     $o_cache->setRedis($o_redis);
     return $o_cache;
 }
コード例 #9
0
 /**
  * Get cache driver.
  *
  * @param array $options
  *
  * @return \Doctrine\Common\Cache\Cache
  */
 protected static function getCacheDriver(array $options)
 {
     $cache = $options['cache_driver'];
     if ($cache === null) {
         if (extension_loaded('apc')) {
             $cache = new \Doctrine\Common\Cache\ApcCache();
         } elseif (extension_loaded('xcache')) {
             $cache = new \Doctrine\Common\Cache\XcacheCache();
         } elseif (extension_loaded('memcache')) {
             $memcache = new \Memcache();
             $memcache->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\MemcacheCache();
             $cache->setMemcache($memcache);
         } elseif (extension_loaded('redis')) {
             $redis = new \Redis();
             $redis->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\RedisCache();
             $cache->setRedis($redis);
         } else {
             $cache = new \Doctrine\Common\Cache\ArrayCache();
         }
     }
     return $cache;
 }
コード例 #10
0
ファイル: module.config.php プロジェクト: fousheezy/common
    return \FzyCommon\Util\Params::create($sm->get('config'));
}, 'FzyCommon\\ModuleConfig' => function ($sm) {
    return $sm->get('FzyCommon\\Config')->getWrapped(Base::MODULE_CONFIG_KEY);
}, 'FzyCommon\\Service\\Aws\\Config' => function ($sm) {
    return $sm->get('FzyCommon\\ModuleConfig')->getWrapped('aws');
}, 'FzyCommon\\Service\\Aws\\S3\\Config' => function ($sm) {
    return $sm->get('FzyCommon\\Service\\Aws\\Config')->getWrapped('s3');
}, 'FzyCommon\\Service\\Aws\\S3' => function ($sm) {
    return S3Client::factory($sm->get('FzyCommon\\Service\\Aws\\S3\\Config')->get());
}, 'FzyCommon\\Factory\\DoctrineCache' => function ($sm) {
    /* @var $config \FzyCommon\Util\Params */
    $config = $sm->get('FzyCommon\\ModuleConfig');
    if ($config->get('production') && class_exists('Redis')) {
        try {
            $redisConfig = $config->getWrapped('doctrine_cache_config');
            $cache = new \Doctrine\Common\Cache\RedisCache();
            $redis = new \Redis();
            $redis->connect($redisConfig->get('host', '127.0.0.1'), $redisConfig->get('port', 6379), $redisConfig->get('timeout', 5));
            $cache->setRedis($redis);
            return $cache;
        } catch (\Exception $e) {
            if ($config->get('debug')) {
                throw $e;
            }
        }
    }
    return new ArrayCache();
}, 'doctrine.cache.fzy_cache' => function ($sm) {
    /* @var $config \FzyCommon\Util\Params */
    $config = $sm->get('FzyCommon\\ModuleConfig');
    return $sm->get($config->get('doctrine_cache', 'FzyCommon\\Factory\\DoctrineCache'));
コード例 #11
0
 public function __construct()
 {
     // load database configuration from CodeIgniter
     require_once APPPATH . 'config/database.php';
     include_once APPPATH . 'third_party/Doctrine/vendor/autoload.php';
     // load the entities
     $entityClassLoader = new ClassLoader('Entity', APPPATH . 'models');
     $entityClassLoader->register();
     // load the proxy entities
     $proxiesClassLoader = new ClassLoader('Proxies', APPPATH . 'models');
     $proxiesClassLoader->register();
     // Set up the configuration
     $config = new Configuration();
     // Set up caches
     if (ENVIRONMENT == 'development') {
         // set environment in index.php
         // set up simple array caching for development mode
         $cacheDriver = new \Doctrine\Common\Cache\ArrayCache();
     } else {
         // set up caching with APC for production mode
         $redis = new Redis();
         $redis->connect('redis_host', 'redis_port');
         $cacheDriver = new \Doctrine\Common\Cache\RedisCache();
         $cacheDriver->setRedis($redis);
     }
     $config->setMetadataCacheImpl($cacheDriver);
     $config->setQueryCacheImpl($cacheDriver);
     $driverImpl = $config->newDefaultAnnotationDriver(APPPATH . 'models/Entity');
     $config->setMetadataDriverImpl($driverImpl);
     // Proxy configuration
     $config->setProxyDir(APPPATH . '/models/Proxies');
     $config->setProxyNamespace('Proxies');
     // Set up logger
     if (ENVIRONMENT == 'development') {
         $logger = new \Doctrine\DBAL\Logging\EchoSQLLogger();
         $config->setSQLLogger($logger);
     }
     $config->setAutoGenerateProxyClasses(true);
     // only for development
     $connectionOptions = array('driver' => 'pdo_mysql', 'user' => $db['default']['username'], 'password' => $db['default']['password'], 'host' => $db['default']['hostname'], 'dbname' => $db['default']['database'], 'charset' => $db['default']['char_set'], 'driverOptions' => array('charset' => $db['default']['char_set']));
     $this->em = EntityManager::create($connectionOptions, $config);
     //        $connection_options = array(
     //            'driver'        => 'pdo_mysql',
     //            'user'          => $db['default']['username'],
     //            'password'      => $db['default']['password'],
     //            'host'          => $db['default']['hostname'],
     //            'dbname'        => $db['default']['database'],
     //            'charset'       => $db['default']['char_set'],
     //            'driverOptions' => array(
     //                'charset'   => $db['default']['char_set'],
     //            ),
     //        );
     //
     //        // With this configuration, your model files need to be in application/models/Entity
     //        // e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
     //        $models_namespace = 'Entity';
     //        $models_path = APPPATH . 'models';
     //        $proxies_dir = APPPATH . 'models/Proxies';
     //        $metadata_paths = array(APPPATH . 'models/Entity');
     //
     //        // Set $dev_mode to TRUE to disable caching while you develop
     //        $dev_mode = true;
     //
     //        // If you want to use a different metadata driver, change createAnnotationMetadataConfiguration
     //        // to createXMLMetadataConfiguration or createYAMLMetadataConfiguration.
     //        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode, $proxies_dir);
     //        $this->em = EntityManager::create($connection_options, $config);
     //
     //        $loader = new ClassLoader($models_namespace, $models_path);
     //        $loader->register();
 }
コード例 #12
0
ファイル: Factory.php プロジェクト: ironedgesoftware/cache
 /**
  * Creates an instance of a doctrine cache provider and assigns it an ID.
  *
  * @param string               $id             - Instance ID.
  * @param string|CacheProvider $typeOrInstance - Instance type.
  * @param array                $config         - Instance config.
  * @param bool                 $refresh        - Re-create the instance even if it's already created.
  *
  * @throws InvalidTypeException
  * @throws InvalidConfigException
  * @throws MissingExtensionException
  *
  * @return CacheProvider
  */
 public function create($id, $typeOrInstance, array $config = [], $refresh = false)
 {
     if (!is_string($id)) {
         throw new \InvalidArgumentException('Argument $id must be a string.');
     }
     if (!is_string($id) && (!is_object($typeOrInstance) || !$typeOrInstance instanceof CacheProvider)) {
         throw new \InvalidArgumentException('Argument $typeOrInstance must be a string or an instance of \\Doctrine\\Common\\Cache\\CacheProvider.');
     }
     if (!isset($this->_instances[$id]) || $refresh) {
         if (is_object($typeOrInstance)) {
             $this->_instances[$id] = $typeOrInstance;
         } else {
             $cache = null;
             switch ($typeOrInstance) {
                 case self::TYPE_APCU:
                     if (!function_exists('apcu_fetch')) {
                         throw MissingExtensionException::create('apcu', 'ApcuCache');
                     }
                     $cache = new \Doctrine\Common\Cache\ApcuCache();
                     break;
                 case self::TYPE_ARRAY:
                     $cache = new \Doctrine\Common\Cache\ArrayCache();
                     break;
                 case self::TYPE_COUCHBASE:
                     if (!class_exists('\\Couchbase')) {
                         throw MissingExtensionException::create('couchbase', 'CouchbaseCache');
                     }
                     $config = array_merge(['couchbase' => null], $config);
                     if (!is_object($config['couchbase']) || !$config['couchbase'] instanceof \Couchbase) {
                         throw InvalidConfigException::create('couchbase', 'an instance of \\Couchbase.');
                     }
                     $cache = new \Doctrine\Common\Cache\CouchbaseCache();
                     $cache->setCouchbase($config['couchbase']);
                     break;
                 case self::TYPE_FILESYSTEM:
                     $config = array_merge(['directory' => null, 'extension' => FilesystemCache::EXTENSION, 'umask' => 02], $config);
                     $cache = new FilesystemCache($config['directory'], $config['extension'], $config['umask']);
                     break;
                 case self::TYPE_MEMCACHE:
                     if (!class_exists('\\Memcache')) {
                         throw MissingExtensionException::create('memcache', 'MemcacheCache');
                     }
                     $config = array_merge(['memcache' => null], $config);
                     if (!is_object($config['memcache']) || !$config['memcache'] instanceof \Memcache) {
                         throw InvalidConfigException::create('memcache', 'an instance of \\Memcache.');
                     }
                     $cache = new \Doctrine\Common\Cache\MemcacheCache();
                     $cache->setMemcache($config['memcache']);
                     break;
                 case self::TYPE_MEMCACHED:
                     if (!class_exists('\\Memcached')) {
                         throw MissingExtensionException::create('memcached', 'MemcachedCache');
                     }
                     $config = array_merge(['memcached' => null], $config);
                     if (!is_object($config['memcached']) || !$config['memcached'] instanceof \Memcached) {
                         throw InvalidConfigException::create('memcached', 'an instance of \\Memcached.');
                     }
                     $cache = new \Doctrine\Common\Cache\MemcachedCache();
                     $cache->setMemcached($config['memcached']);
                     break;
                 case self::TYPE_MONGODB:
                     if (!class_exists('\\MongoCollection')) {
                         throw MissingExtensionException::create('mongo', 'MongoDBCache');
                     }
                     $config = array_merge(['mongoCollection' => null], $config);
                     if (!is_object($config['mongoCollection']) || !$config['mongoCollection'] instanceof \MongoCollection) {
                         throw InvalidConfigException::create('mongoCollection', 'an instance of \\MongoCollection.');
                     }
                     $cache = new \Doctrine\Common\Cache\MongoDBCache($config['mongoCollection']);
                     break;
                 case self::TYPE_PHP_FILE:
                     $config = array_merge(['directory' => null, 'extension' => PhpFileCache::EXTENSION, 'umask' => 02], $config);
                     $cache = new PhpFileCache($config['directory'], $config['extension'], $config['umask']);
                     break;
                 case self::TYPE_PREDIS:
                     if (!class_exists('\\Predis\\ClientInterface')) {
                         throw MissingExtensionException::create('predis', 'PredisCache');
                     }
                     $config = array_merge(['predisClient' => null], $config);
                     if (!is_object($config['predisClient']) || !$config['predisClient'] instanceof \Predis\ClientInterface) {
                         throw InvalidConfigException::create('predisClient', 'an instance of \\Predis\\ClientInterface.');
                     }
                     $cache = new \Doctrine\Common\Cache\PredisCache($config['predisClient']);
                     break;
                 case self::TYPE_REDIS:
                     if (!class_exists('\\Redis')) {
                         throw MissingExtensionException::create('redis', 'RedisCache');
                     }
                     $config = array_merge(['redis' => null], $config);
                     if (!is_object($config['redis']) || !$config['redis'] instanceof \Redis) {
                         throw InvalidConfigException::create('redis', 'an instance of \\Redis.');
                     }
                     $cache = new \Doctrine\Common\Cache\RedisCache();
                     $cache->setRedis($config['redis']);
                     break;
                 case self::TYPE_RIAK:
                     if (!class_exists('\\Riak\\Bucket')) {
                         throw MissingExtensionException::create('riak', 'RiakCache');
                     }
                     $config = array_merge(['riakBucket' => null], $config);
                     if (!is_object($config['riakBucket']) || !$config['riakBucket'] instanceof \Riak\Bucket) {
                         throw InvalidConfigException::create('riakBucket', 'an instance of \\Riak\\Bucket.');
                     }
                     $cache = new \Doctrine\Common\Cache\RiakCache($config['riakBucket']);
                     break;
                 case self::TYPE_SQLITE3:
                     if (!class_exists('\\SQLite3')) {
                         throw MissingExtensionException::create('sqlite3', 'SQLite3Cache');
                     }
                     $config = array_merge(['sqlite3' => null, 'sqlite3Table' => null], $config);
                     if (!is_object($config['sqlite3']) || !$config['sqlite3'] instanceof \SQLite3) {
                         throw InvalidConfigException::create('sqlite3', 'an instance of \\SQLite3.');
                     }
                     if (!is_string($config['sqlite3Table']) || $config['sqlite3Table'] === '') {
                         throw InvalidConfigException::create('sqlite3Table', 'a non-empty string.');
                     }
                     $cache = new \Doctrine\Common\Cache\SQLite3Cache($config['sqlite3'], $config['sqlite3Table']);
                     break;
                 case self::TYPE_VOID:
                     $cache = new VoidCache();
                     break;
                 case self::TYPE_WINCACHE:
                     if (!function_exists('wincache_ucache_get')) {
                         throw MissingExtensionException::create('wincache', 'WinCacheCache');
                     }
                     $cache = new \Doctrine\Common\Cache\WinCacheCache();
                     break;
                 case self::TYPE_XCACHE:
                     if (!function_exists('xcache_isset')) {
                         throw MissingExtensionException::create('xcache', 'XcacheCache');
                     }
                     $cache = new \Doctrine\Common\Cache\XcacheCache();
                     break;
                 case self::TYPE_ZEND_DATA:
                     if (!function_exists('zend_shm_cache_fetch')) {
                         throw new \RuntimeException('Zend Data component must be installed and available before using this Cache Driver.');
                     }
                     $cache = new \Doctrine\Common\Cache\ZendDataCache();
                     break;
                 default:
                     throw InvalidTypeException::create($typeOrInstance);
             }
             $this->_instances[$id] = $cache;
         }
     }
     return $this->_instances[$id];
 }
コード例 #13
0
ファイル: Bootstrap.php プロジェクト: konstantin-pr/Ses
 public static function initDoctrineCache($config)
 {
     $cache = null;
     if (isset(App::$inst->config['resources']['doctrine']['orm']['cache']['adapter'])) {
         switch (App::$inst->config['resources']['doctrine']['orm']['cache']['adapter']) {
             case 'Doctrine\\Common\\Cache\\MemcacheCache':
                 if (is_null(App::$inst->memcache)) {
                     return false;
                 }
                 $cache = new \Doctrine\Common\Cache\MemcacheCache();
                 $cache->setMemcache(App::$inst->memcache);
                 break;
             case 'Doctrine\\Common\\Cache\\RedisCache':
                 if (is_null(App::$inst->redis)) {
                     return false;
                 }
                 $cache = new \Doctrine\Common\Cache\RedisCache();
                 $cache->setRedis(App::$inst->redis);
                 break;
             case 'Doctrine\\Common\\Cache\\ApcCache':
                 $cache = new \Doctrine\Common\Cache\ApcCache();
                 break;
             default:
                 $cache = new \Doctrine\Common\Cache\ArrayCache();
                 break;
         }
     } else {
         $cache = new \Doctrine\Common\Cache\ArrayCache();
     }
     $config->setQueryCacheImpl($cache);
     $config->setResultCacheImpl($cache);
     $config->setMetadataCacheImpl($cache);
     return $cache;
 }
コード例 #14
0
 /**
  * Initialize Doctrine entity manager in DI container.
  *
  * This method can be called from InstallApp after updating
  * doctrine configuration.
  *
  * @param Pimple\Container $container [description]
  */
 public function register(Container $container)
 {
     if ($container['config'] !== null && isset($container['config']["doctrine"])) {
         $container['em.config'] = function ($c) {
             $config = Setup::createAnnotationMetadataConfiguration($c['entitiesPaths'], (bool) $c['config']['devMode'], ROADIZ_ROOT . '/gen-src/Proxies', null, false);
             $config->setProxyDir(ROADIZ_ROOT . '/gen-src/Proxies');
             $config->setProxyNamespace('Proxies');
             return $config;
         };
         $container['em'] = function ($c) {
             try {
                 $c['stopwatch']->start('initDoctrine');
                 $em = EntityManager::create($c['config']["doctrine"], $c['em.config']);
                 $evm = $em->getEventManager();
                 /*
                  * Create dynamic dicriminator map for our Node system
                  */
                 $evm->addEventListener(Events::loadClassMetadata, new DataInheritanceEvent());
                 $resultCacheDriver = $em->getConfiguration()->getResultCacheImpl();
                 if ($resultCacheDriver !== null) {
                     $resultCacheDriver->setNamespace($c['config']["appNamespace"]);
                 }
                 $hydratationCacheDriver = $em->getConfiguration()->getHydrationCacheImpl();
                 if ($hydratationCacheDriver !== null) {
                     $hydratationCacheDriver->setNamespace($c['config']["appNamespace"]);
                 }
                 $queryCacheDriver = $em->getConfiguration()->getQueryCacheImpl();
                 if ($queryCacheDriver !== null) {
                     $queryCacheDriver->setNamespace($c['config']["appNamespace"]);
                 }
                 $metadataCacheDriver = $em->getConfiguration()->getMetadataCacheImpl();
                 if (null !== $metadataCacheDriver) {
                     $metadataCacheDriver->setNamespace($c['config']["appNamespace"]);
                 }
                 $c['stopwatch']->stop('initDoctrine');
                 return $em;
             } catch (\PDOException $e) {
                 $c['session']->getFlashBag()->add('error', $e->getMessage());
                 return null;
             }
         };
     }
     /*
      * logic from Doctrine setup method
      *
      * https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Setup.php#L122
      */
     $container['nodesSourcesUrlCacheProvider'] = function ($c) {
         if (true === (bool) $c['config']['devMode']) {
             $cache = new ArrayCache();
         } else {
             if (extension_loaded('apc')) {
                 $cache = new \Doctrine\Common\Cache\ApcCache();
             } elseif (extension_loaded('xcache')) {
                 $cache = new \Doctrine\Common\Cache\XcacheCache();
             } elseif (extension_loaded('memcache')) {
                 $memcache = new \Memcache();
                 $memcache->connect('127.0.0.1');
                 $cache = new \Doctrine\Common\Cache\MemcacheCache();
                 $cache->setMemcache($memcache);
             } elseif (extension_loaded('redis')) {
                 $redis = new \Redis();
                 $redis->connect('127.0.0.1');
                 $cache = new \Doctrine\Common\Cache\RedisCache();
                 $cache->setRedis($redis);
             } else {
                 $cache = new ArrayCache();
             }
         }
         if ($cache instanceof CacheProvider) {
             $cache->setNamespace($c['config']["appNamespace"] . "_nsurls");
             // to avoid collisions
         }
         return $cache;
     };
     return $container;
 }
コード例 #15
0
ファイル: Cache.php プロジェクト: hansioan/slidebasedocs
 /**
  * Automatically picks the cache mechanism to use.  If you pick one manually it will use that
  * If there is no config option for $driver in the config, or it's set to 'auto', it will
  * pick the best option based on which cache extensions are installed.
  *
  * @return DoctrineCacheDriver  The cache driver to use
  */
 public function getCacheDriver()
 {
     $setting = $this->config->get('system.cache.driver');
     $driver_name = 'file';
     if (!$setting || $setting == 'auto') {
         if (extension_loaded('apcu')) {
             $driver_name = 'apcu';
         } elseif (extension_loaded('apc')) {
             $driver_name = 'apc';
         } elseif (extension_loaded('wincache')) {
             $driver_name = 'wincache';
         } elseif (extension_loaded('xcache')) {
             $driver_name = 'xcache';
         }
     } else {
         $driver_name = $setting;
     }
     $this->driver_name = $driver_name;
     switch ($driver_name) {
         case 'apc':
             $driver = new \Doctrine\Common\Cache\ApcCache();
             break;
         case 'apcu':
             $driver = new \Doctrine\Common\Cache\ApcuCache();
             break;
         case 'wincache':
             $driver = new \Doctrine\Common\Cache\WinCacheCache();
             break;
         case 'xcache':
             $driver = new \Doctrine\Common\Cache\XcacheCache();
             break;
         case 'memcache':
             $memcache = new \Memcache();
             $memcache->connect($this->config->get('system.cache.memcache.server', 'localhost'), $this->config->get('system.cache.memcache.port', 11211));
             $driver = new \Doctrine\Common\Cache\MemcacheCache();
             $driver->setMemcache($memcache);
             break;
         case 'redis':
             $redis = new \Redis();
             $redis->connect($this->config->get('system.cache.redis.server', 'localhost'), $this->config->get('system.cache.redis.port', 6379));
             $driver = new \Doctrine\Common\Cache\RedisCache();
             $driver->setRedis($redis);
             break;
         default:
             $driver = new \Doctrine\Common\Cache\FilesystemCache($this->cache_dir);
             break;
     }
     return $driver;
 }
コード例 #16
0
ファイル: Cache.php プロジェクト: cv0/fansoro
 /**
  * Get Cache Driver
  *
  * @access public
  * @return object
  */
 public static function getCacheDriver()
 {
     $driver_name = Config::get('system.cache.driver');
     if (!$driver_name || $driver_name == 'auto') {
         if (extension_loaded('apc')) {
             $driver_name = 'apc';
         } elseif (extension_loaded('wincache')) {
             $driver_name = 'wincache';
         } elseif (extension_loaded('xcache')) {
             $driver_name = 'xcache';
         }
     } else {
         $driver_name = 'file';
     }
     switch ($driver_name) {
         case 'apc':
             $driver = new \Doctrine\Common\Cache\ApcCache();
             break;
         case 'wincache':
             $driver = new \Doctrine\Common\Cache\WinCacheCache();
             break;
         case 'xcache':
             $driver = new \Doctrine\Common\Cache\XcacheCache();
             break;
         case 'memcache':
             $memcache = new \Memcache();
             $memcache->connect(Config::get('system.cache.memcache.server', 'localhost'), Config::get('system.cache.memcache.port', 11211));
             $driver = new \Doctrine\Common\Cache\MemcacheCache();
             $driver->setMemcache($memcache);
             break;
         case 'redis':
             $redis = new \Redis();
             $redis->connect(Config::get('system.cache.redis.server', 'localhost'), Config::get('system.cache.redis.port', 6379));
             $driver = new \Doctrine\Common\Cache\RedisCache();
             $driver->setRedis($redis);
             break;
         default:
             // Create doctrine cache directory if its not exists
             !Dir::exists($cache_directory = CACHE_PATH . '/doctrine/') and Dir::create($cache_directory);
             $driver = new \Doctrine\Common\Cache\FilesystemCache($cache_directory);
             break;
     }
     return $driver;
 }
コード例 #17
0
ファイル: doctrine.php プロジェクト: kohana/doctrine
        case 'memcache':
            $memcache = new Memcache();
            $memcache->connect($settings["host"], $settings["port"]);
            $Cache = new \Doctrine\Common\Cache\MemcacheCache();
            $Cache->setMemcache($memcache);
            break;
        case 'xcache':
            $Cache = \Doctrine\Common\Cache\XcacheCache();
            break;
        case 'redis':
            if (!class_exists("Redis")) {
                throw new Exception("Redis cache is not available");
            }
            $redis = new Redis();
            $redis->connect($settings["host"], $settings["port"]);
            $Cache = new \Doctrine\Common\Cache\RedisCache();
            $Cache->setRedis($redis);
    }
    // Build configuration
    $Configuration->setMetadataCacheImpl($Cache);
    $Configuration->setProxyDir($config["proxy"]["path"]);
    $Configuration->setProxyNamespace($config["proxy"]["namespace"]);
    $Configuration->setMetadataDriverImpl($mapping);
    // Create EntityManager
    $em = \Doctrine\ORM\EntityManager::create($config["credentials"], $Configuration);
    // Set all helpers
    $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)));
    $helperSet = $helperSet ?: new \Symfony\Component\Console\Helper\HelperSet();
    // Run console
    \Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);
} catch (Exception $e) {
コード例 #18
0
ファイル: Setup.php プロジェクト: karvannan-thi/doctrine2
 /**
  * Creates a configuration without a metadata driver.
  *
  * @param bool   $isDevMode
  * @param string $proxyDir
  * @param Cache  $cache
  *
  * @return Configuration
  */
 public static function createConfiguration($isDevMode = false, $proxyDir = null, Cache $cache = null)
 {
     $proxyDir = $proxyDir ?: sys_get_temp_dir();
     if ($isDevMode === false && $cache === null) {
         if (extension_loaded('apc')) {
             $cache = new \Doctrine\Common\Cache\ApcCache();
         } elseif (extension_loaded('xcache')) {
             $cache = new \Doctrine\Common\Cache\XcacheCache();
         } elseif (extension_loaded('memcache')) {
             $memcache = new \Memcache();
             $memcache->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\MemcacheCache();
             $cache->setMemcache($memcache);
         } elseif (extension_loaded('redis')) {
             $redis = new \Redis();
             $redis->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\RedisCache();
             $cache->setRedis($redis);
         } else {
             $cache = new ArrayCache();
         }
     } elseif ($cache === null) {
         $cache = new ArrayCache();
     }
     if ($cache instanceof CacheProvider) {
         $cache->setNamespace("dc2_" . md5($proxyDir) . "_");
         // to avoid collisions
     }
     $config = new Configuration();
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     $config->setResultCacheImpl($cache);
     $config->setProxyDir($proxyDir);
     $config->setProxyNamespace('DoctrineProxies');
     $config->setAutoGenerateProxyClasses($isDevMode);
     return $config;
 }
コード例 #19
0
 /**
  * 
  * 获取缓存信息
  * @return \Doctrine\Common\Cache\MongoDBCache
  */
 protected function getCache()
 {
     $namespace = 'PanGuKTD_ORM_';
     $cacheConfig = config('doctrine');
     $cacheName = $cacheConfig['name'];
     $cache = null;
     if ($cacheName == 'array') {
         $cache = new \Doctrine\Common\Cache\ArrayCache();
     } elseif ($cacheName == 'xcache') {
         $cache = new \Doctrine\Common\Cache\XcacheCache();
     } elseif ($cacheName == 'memcached') {
         $memcached = new \Memcached();
         $memcached->addServers($cacheConfig['memcached']);
         $cache = new \Doctrine\Common\Cache\MemcachedCache();
         $cache->setMemcached($memcached);
         $cache->setNamespace($namespace);
     } elseif ($cacheName == 'memcache') {
         $memcache = new \Memcache();
         foreach ($cacheConfig['memcache'] as $key => $value) {
             $memcache->addServer($value['host'], $value['port'], $value['persistent'], $value['weight']);
         }
         $cache = new \Doctrine\Common\Cache\MemcacheCache();
         $cache->setMemcache($memcache);
         $cache->setNamespace($namespace);
     } elseif ($cacheName == 'apc') {
         $cache = new \Doctrine\Common\Cache\ApcCache();
         $cache->setNamespace($namespace);
     } elseif ($cacheName == 'mongo') {
         $host = $cacheConfig['mongo']['host'];
         $port = $cacheConfig['mongo']['port'];
         $opt = $cacheConfig['mongo']['options'];
         $mongo = new \MongoClient("mongodb://{$host}:{$port}", $opt);
         $mongo = new \MongoDB($mongo, 'doctrine_orm_cache');
         $conn = new \MongoCollection($mongo, $namespace);
         $cache = new \Doctrine\Common\Cache\MongoDBCache($conn);
         $cache->setNamespace($namespace);
     } elseif ($cacheName == 'redis') {
         $host = $cacheConfig['redis']['host'];
         $port = $cacheConfig['redis']['port'];
         $redis = new \Redis();
         $redis->connect($host, $port);
         $cache = new \Doctrine\Common\Cache\RedisCache();
         $cache->setRedis($redis);
     }
     return $cache;
 }