Example #1
0
 static function getEM()
 {
     if (is_null(self::$em)) {
         // the connection configuration
         $dbParams = array('driver' => 'pdo_mysql', 'user' => Config::singleton()->get("dbuser"), 'password' => Config::singleton()->get("dbpass"), 'dbname' => Config::singleton()->get("dbname"), 'database_host' => Config::singleton()->get("dbhost"));
         $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array("app/models"), Config::singleton()->get("debug"));
         self::$em = Doctrine\ORM\EntityManager::create($dbParams, $config);
         $emConfig = self::$em->getConfiguration();
         $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\\Query\\Mysql\\Year');
         $emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\\Query\\Mysql\\Month');
         $emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\\Query\\Mysql\\Day');
         $emConfig->addCustomDatetimeFunction('Date', 'Date');
     }
     return self::$em;
 }
 public static function createEntityManager()
 {
     $config = new Doctrine\ORM\Configuration();
     // annotations
     $annotationDriver = $config->newDefaultAnnotationDriver(APP_DIR . '/models');
     $config->setMetadataDriverImpl($annotationDriver);
     $config->setProxyNamespace('GriditoExample\\Doctrine\\Proxy');
     $config->setProxyDir(TEMP_DIR . '/cache');
     // cache
     $cache = new Doctrine\Common\Cache\ArrayCache();
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     // entity manager
     return Doctrine\ORM\EntityManager::create(array("driver" => "pdo_sqlite", "path" => APP_DIR . "/models/users.s3db"), $config);
 }
Example #3
0
function GetEntityManager()
{
    $namespaces = array(__DIR__ . '/../config/yaml' => 'AppBundle\\Entity');
    // $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
    // $config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
    // $config = Setup::createYAMLMetadataConfiguration($paths, $isDevMode);
    $config = new Doctrine\ORM\Configuration();
    $driverImpl = new Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver($namespaces);
    $config->setMetadataDriverImpl($driverImpl);
    $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
    $config->setProxyDir(DOCTRINE_PROXY_DIR);
    $config->setProxyNamespace(DOCTRINE_PROXY_NAMESPACE);
    // the connection configuration
    $dbParams = array('driver' => MYSQL_DRIVER, 'host' => MYSQL_HOST, 'port' => MYSQL_PORT, 'user' => MYSQL_USER, 'password' => MYSQL_PASSWORD, 'dbname' => MYSQL_SCHEMA_NAME);
    return Doctrine\ORM\EntityManager::create($dbParams, $config);
}
Example #4
0
 /**
  * Creates and returns a new instance of doctrine
  * @return EntityManager The Doctrine Entity Manager
  */
 public function getDoctrineEntityManager()
 {
     try {
         require_once PATH_3RD_PARTY . '/doctrine-orm/vendor/autoload.php';
         $config = Doctrine\ORM\Tools\Setup::createYAMLMetadataConfiguration(array(PATH_INCLUDE . '/models/mapping/yml'), true);
         $config->setProxyDir(PATH_INCLUDE . '/models/Proxies');
         $config->setProxyNamespace('Babesk\\Proxies');
         $config->addEntityNamespace('DM', 'Babesk\\ORM');
         $conn = array('driver' => 'pdo_mysql', 'dbname' => $this->_databaseName, 'user' => $this->_username, 'password' => $this->_password, 'host' => $this->_host);
         $loader = new \Doctrine\Common\ClassLoader('Babesk', PATH_INCLUDE . '/models/Entities');
         $loader->register();
         $loader = new \Doctrine\Common\ClassLoader('Repository', PATH_INCLUDE . '/models');
         $loader->register();
         $entityManager = Doctrine\ORM\EntityManager::create($conn, $config);
         $entityManager->getEventManager()->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit('utf8', 'utf8_unicode_ci'));
         return $entityManager;
     } catch (Exception $e) {
         throw new Exception('Could not set up doctrine entity manager!');
     }
 }
 public function initialize()
 {
     require_once "vendor/autoload.php";
     $config = new Doctrine\ORM\Configuration();
     $driverImpl = $config->newDefaultAnnotationDriver(__DIR__ . '/models');
     $config->setMetadataDriverImpl($driverImpl);
     //$config->setQueryCacheImpl($cache);
     $config->setProxyDir(__DIR__ . '/proxies');
     $config->setProxyNamespace('Proxies');
     $config->setAutoGenerateProxyClasses(false);
     // no code generation in production
     $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true);
     $this->em = Doctrine\ORM\EntityManager::create($dbParams, $config);
     if (!self::$classes) {
         self::$classes = $this->em->getMetadataFactory()->getAllMetadata();
     }
     $schemaTool = new Doctrine\ORM\Tools\SchemaTool($this->em);
     $schemaTool->createSchema(self::$classes);
     require_once __DIR__ . '/proxies/__CG__Author.php';
 }
Example #6
0
<?php

require "Doctrine/ORM/Tools/Setup.php";
Doctrine\ORM\Tools\Setup::registerAutoloadDirectory('.');
//  use Doctrine\ORM\Tools\Setup;
//  use Doctrine\ORM\EntityManager;
$isDevMode = true;
// the connection configuration
$dbParams = array('driver' => 'pdo_mysql', 'user' => 'lab', 'password' => '7DULcn6NaWdvVxaN', 'dbname' => 'lab', 'host' => 'localhost');
//$config = Setup::createAnnotationMetadataConfiguration(array('config/Entities/'), $isDevMode);
$config = Doctrine\ORM\Tools\Setup::createYAMLMetadataConfiguration(array('config/yml/'), $isDevMode);
$em = Doctrine\ORM\EntityManager::create($dbParams, $config);
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)));
include "ORM/load.php";
Example #7
0
 protected function _initDoctrine()
 {
     require_once LIBRARY_PATH . '/Doctrine/Common/ClassLoader.php';
     $autoloader = \Zend_Loader_Autoloader::getInstance();
     $fmmAutoloader = new \Doctrine\Common\ClassLoader();
     $autoloader->pushAutoloader(array($fmmAutoloader, 'loadClass'));
     $options = $this->getOptions();
     $config = new Doctrine\ORM\Configuration();
     $config->addCustomDatetimeFunction('YEAR', 'Doctrine\\Extensions\\Query\\Mysql\\Year');
     $config->addCustomDatetimeFunction('MONTH', 'Doctrine\\Extensions\\Query\\Mysql\\Month');
     $config->addCustomDatetimeFunction('DAY', 'Doctrine\\Extensions\\Query\\Mysql\\Day');
     $config->addCustomStringFunction('DATEDIFF', 'Doctrine\\Extensions\\Query\\Mysql\\DateDiff');
     $config->addCustomStringFunction('DATE_FORMAT', 'Doctrine\\Extensions\\Query\\Mysql\\DateFormat');
     $config->addCustomStringFunction('IF', 'Doctrine\\Extensions\\Query\\Mysql\\IfElse');
     $config->addCustomStringFunction('GROUP_CONCAT', 'Doctrine\\Extensions\\Query\\Mysql\\GroupConcat');
     $config->addCustomStringFunction('IFNULL', 'Doctrine\\Extensions\\Query\\Mysql\\IfNull');
     $config->setProxyDir($options['doctrine']['metadata']['proxyDir']);
     $config->setProxyNamespace('Doctrine\\Proxy');
     $config->setAutoGenerateProxyClasses(true);
     $config->setAutoGenerateProxyClasses(APPLICATION_ENV == 'development');
     //$driverImpl = $config->newDefaultAnnotationDriver($options['metadata']['entityDir']);
     $driverImpl = new Doctrine\ORM\Mapping\Driver\YamlDriver($options['doctrine']['metadata']['entityDir']);
     $config->setMetadataDriverImpl($driverImpl);
     $cache = new Doctrine\Common\Cache\ArrayCache();
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     $evm = new Doctrine\Common\EventManager();
     $em = Doctrine\ORM\EntityManager::create($options['doctrine']['db'], $config, $evm);
     Zend_Registry::set('doctrine', $em);
     return $em;
 }
Example #8
0
<?php

require_once 'vendor/autoload.php';
use Doctrine\Orm\Tools\Setup, Doctrine\Common\EventManager, Doctrine\ORM\Events, Doctrine\ORM\Configuration, Doctrine\Common\Cache\ArrayCache as Cache, Doctrine\Common\Annotations\AnnotationRegistry, Doctrine\Common\Annotations\AnnotationReader, Doctrine\Common\Annotations\CachedReader, Doctrine\ORM\Mapping\Driver\AnnotationDriver, Doctrine\Common\ClassLoader;
$cache = new Cache();
$annotationReader = new AnnotationReader();
$cachedAnnotationReader = new CachedReader($annotationReader, $cache);
$annotationDriver = new AnnotationDriver($cachedAnnotationReader, array(__DIR__ . DIRECTORY_SEPARATOR . 'src'));
$driverChain = new \Doctrine\ORM\Mapping\Driver\DriverChain();
$driverChain->addDriver($annotationDriver, 'Code');
$config = new Configuration();
$config->setProxyDir('/tmp');
$config->setProxyNamespace('Proxy');
$config->setAutoGenerateProxyClasses(true);
// this can be based on production config.
// register metadata driver
$config->setMetadataDriverImpl($driverChain);
// use our allready initialized cache driver
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
AnnotationRegistry::registerFile(__DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'doctrine' . DIRECTORY_SEPARATOR . 'orm' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Doctrine' . DIRECTORY_SEPARATOR . 'ORM' . DIRECTORY_SEPARATOR . 'Mapping' . DIRECTORY_SEPARATOR . 'Driver' . DIRECTORY_SEPARATOR . 'DoctrineAnnotations.php');
$evm = new EventManager();
$em = Doctrine\ORM\EntityManager::create(array('driver' => 'pdo_mysql', 'host' => 'localhost', 'port' => '3306', 'user' => 'root', 'password' => '', 'dbname' => 'son-doctrine'), $config, $evm);
$app = new \Silex\Application();
$app['debug'] = true;
$app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
$app->register(new \Silex\Provider\UrlGeneratorServiceProvider());
return $app;
<?php

return [\Doctrine\ORM\EntityManager::class => function (\Domynation\Config\ConfigInterface $config) {
    $devMode = !IS_PRODUCTION;
    $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($config->get('entityDirectories'), $devMode);
    if (IS_PRODUCTION) {
        $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcuCache());
        $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ApcuCache());
    }
    // Uncomment the following to debug every request made to the DB
    //$config->setSQLLogger(new Doctrine\DBAL\Logging\EchoSQLLogger);
    return Doctrine\ORM\EntityManager::create(['driver' => DB_DRIVER, 'dbname' => DB_DATABASE, 'user' => DB_USER, 'password' => DB_PASSWORD], $config);
}, \Doctrine\DBAL\Connection::class => function () {
    $db = \Doctrine\DBAL\DriverManager::getConnection(['driver' => DB_DRIVER, 'dbname' => DB_DATABASE, 'user' => DB_USER, 'password' => DB_PASSWORD], new \Doctrine\DBAL\Configuration());
    // @todo: Extremely ugly hack until all the event listeners are refactored.
    \Event::setDatabase($db);
    return $db;
}, \Domynation\Bus\CommandBusInterface::class => function (\Interop\Container\ContainerInterface $container, \Domynation\Authentication\AuthenticatorInterface $auth, \Domynation\Eventing\EventDispatcherInterface $dispatcher, \Domynation\Cache\CacheInterface $cache) {
    $busLogger = new Monolog\Logger('Bus_logger');
    $busLogger->pushHandler(new Monolog\Handler\StreamHandler(PATH_BASE . '/logs/bus.log', Monolog\Logger::INFO));
    return new Domynation\Bus\BasicCommandBus($container, $dispatcher, [new \Domynation\Bus\Middlewares\AuthorizationMiddleware($auth), new \Domynation\Bus\Middlewares\CachingMiddleware($cache), new \Domynation\Bus\Middlewares\LoggingMiddleware($busLogger, $auth), new \Domynation\Bus\Middlewares\HandlingMiddleware()]);
}, \Domynation\Http\Router::class => function (\Interop\Container\ContainerInterface $container, \Domynation\Authentication\UserInterface $user) {
    $routerLogger = new Monolog\Logger('Router_logger');
    $routerLogger->pushHandler(new Monolog\Handler\StreamHandler(PATH_BASE . '/logs/router.log', Monolog\Logger::INFO));
    return new \Domynation\Http\Router($container, new \Domynation\Http\AuthenticationMiddleware($user), new \Domynation\Http\AuthorizationMiddleware($user), new \Domynation\Http\ValidationMiddleware($container), new \Domynation\Http\LoggingMiddleware($routerLogger, $user), new \Domynation\Http\HandlingMiddleware($container));
}, \Domynation\Cache\CacheInterface::class => function () {
    switch (CACHE_DRIVER) {
        case 'redis':
            return new \Domynation\Cache\RedisCache(REDIS_HOST, REDIS_PORT);
        default:
            return new \Domynation\Cache\InMemoryCache();
Example #10
0
 private static function newConnect()
 {
     $dir = __DIR__ . '/../../libs/Doctrine/';
     $vendorPath = realpath($dir);
     $ExtensionPath = realpath($dir . '/DoctrineExtensions');
     require_once $vendorPath . '/Doctrine/Common/ClassLoader.php';
     // autoload all vendors
     $loader = new Doctrine\Common\ClassLoader('Doctrine\\Common', $vendorPath);
     $loader->register();
     $loader = new Doctrine\Common\ClassLoader('Doctrine\\DBAL', $vendorPath);
     $loader->register();
     $loader = new Doctrine\Common\ClassLoader('Doctrine\\ORM', $vendorPath);
     $loader->register();
     // gedmo extensions
     $loader = new Doctrine\Common\ClassLoader('Gedmo', $ExtensionPath);
     $loader->register();
     // Pagefanta
     $classLoader = new Doctrine\Common\ClassLoader("Pagerfanta", $ExtensionPath);
     $classLoader->register();
     //MYSQL Functions
     $classLoader = new \Doctrine\Common\ClassLoader('DoctrineExtensions', realpath($dir));
     $classLoader->register();
     // autoloader for Entity namespace
     $loader = new Doctrine\Common\ClassLoader('Entities', $dir);
     $loader->register();
     // ensure standard doctrine annotations are registered
     Doctrine\Common\Annotations\AnnotationRegistry::registerFile($vendorPath . '/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
     // Second configure ORM
     // globally used cache driver
     $cache = new Doctrine\Common\Cache\ArrayCache();
     $reader = new \Doctrine\Common\Annotations\AnnotationReader();
     Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace('Gedmo\\Mapping\\Annotation', $ExtensionPath);
     $driverChain = new \Doctrine\ORM\Mapping\Driver\DriverChain();
     $annotationDriver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array($dir . 'Entities', $ExtensionPath . '/Gedmo/Tree/Entity'));
     // drivers
     $driverChain->addDriver($annotationDriver, 'Gedmo\\Tree\\Entity');
     $driverChain->addDriver($annotationDriver, 'Entities');
     // general ORM configuration
     $config = new Doctrine\ORM\Configuration();
     //$config->setProxyDir(sys_get_temp_dir());
     $config->setProxyDir($dir . '/Proxies');
     $config->setProxyNamespace('Proxy');
     $config->setAutoGenerateProxyClasses(true);
     // this can be based on production config. FALSE
     // register metadata driver
     $config->setMetadataDriverImpl($driverChain);
     // use our allready initialized cache driver
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     // Third, create event manager and hook prefered extension listeners
     $evm = new Doctrine\Common\EventManager();
     // gedmo extension listeners
     // tree
     $treeListener = new Gedmo\Tree\TreeListener();
     $treeListener->setAnnotationReader($reader);
     $evm->addEventSubscriber($treeListener);
     // timestampable
     $timestampableListener = new Gedmo\Timestampable\TimestampableListener();
     $timestampableListener->setAnnotationReader($reader);
     $evm->addEventSubscriber($timestampableListener);
     // mysql set names UTF-8 if required
     $evm->addEventSubscriber(new Doctrine\DBAL\Event\Listeners\MysqlSessionInit());
     // Finally, create entity manager
     $connection = array('dbname' => DB_DATABASE, 'user' => DB_USER, 'password' => DB_PASSWORD, 'host' => DB_HOST, 'driver' => 'pdo_mysql');
     $config->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\\Query\\Mysql\\Year');
     $config->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\\Query\\Mysql\\Month');
     $config->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\\Query\\Mysql\\Day');
     $config->addCustomDatetimeFunction('HOUR', 'DoctrineExtensions\\Query\\Mysql\\Hour');
     $config->addCustomDatetimeFunction('DATE', 'DoctrineExtensions\\Query\\Mysql\\Date');
     $config->addCustomDatetimeFunction('DATEDIFF', 'DoctrineExtensions\\Query\\MySql\\DateDiff');
     try {
         $em = Doctrine\ORM\EntityManager::create($connection, $config, $evm);
     } catch (Exception $e) {
     }
     self::$EntityManager = $em;
 }
define('VENDOR_PATH', __DIR__ . '/../../vendor/');
define('APP_PATH', __DIR__ . '/../../app/');
define('CONFIG_PATH', __DIR__ . '/../../app/config/');
define('TEMPLATE_PATH', __DIR__ . '/../../web/views/');
define('PUBLIC_PATH', __DIR__ . '/../../public/');
// Password hasing
define("PBKDF2_HASH_ALGORITHM", "sha256");
define("PBKDF2_ITERATIONS", 1000);
define("PBKDF2_SALT_BYTE_SIZE", 24);
define("PBKDF2_HASH_BYTE_SIZE", 24);
define("HASH_SECTIONS", 4);
define("HASH_ALGORITHM_INDEX", 0);
define("HASH_ITERATION_INDEX", 1);
define("HASH_SALT_INDEX", 2);
define("HASH_PBKDF2_INDEX", 3);
// Registrer autoloaders
require VENDOR_PATH . 'autoload.php';
// Load environment variables
try {
    (new Dotenv\Dotenv(ROOT_PATH))->load();
} catch (Exception $e) {
    echo $e;
}
$config = ['path.root' => ROOT_PATH, 'path.public' => PUBLIC_PATH, 'path.app' => APP_PATH];
require CONFIG_PATH . 'slim.php';
require CONFIG_PATH . 'doctrine.php';
$setup = Doctrine\ORM\Tools\Setup::createYAMLMetadataConfiguration([APP_PATH . 'models/schemas'], getenv('APP_DEBUG'));
$em = \Service\Registry::set('em', Doctrine\ORM\EntityManager::create($config['doctrine'], $setup));
$app = \Service\Registry::set('slim', new \Slim\Slim($config['slim']));
require APP_PATH . 'routes.php';
return $app;
Example #12
0
 public function _initDoctrine()
 {
     $event = $this->profiler->startEvent('Init library: Doctrine');
     $loader = new Doctrine\Common\ClassLoader('Entity', $this->config->db->doctrine->entity);
     $loader->register();
     $loader = new Doctrine\Common\ClassLoader('EntityProxy', $this->config->db->doctrine->entityProxy);
     $loader->register();
     $config = new Doctrine\ORM\Configuration();
     $cache = new Doctrine\Common\Cache\ArrayCache();
     $config->setQueryCacheImpl($cache);
     $config->setProxyDir($this->config->db->doctrine->entityProxy);
     $config->setProxyNamespace('EntityProxy');
     $config->setAutoGenerateProxyClasses(true);
     Doctrine\Common\Annotations\AnnotationRegistry::registerFile(LIBRARY_PATH . '/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
     $driver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(new Doctrine\Common\Annotations\AnnotationReader(), array($this->config->db->doctrine->entity));
     $config->setMetadataDriverImpl($driver);
     $config->setMetadataCacheImpl($cache);
     $em = Doctrine\ORM\EntityManager::create($this->config->db->params->toArray(), $config);
     Yaf\Registry::set('entityManager', $em);
     $this->profiler->endEvent($event);
 }
Example #13
0
$app['translator']->addLoader('yaml', new Symfony\Component\Translation\Loader\YamlFileLoader());
/*** Application Translator ***/
$app['application.translator'] = $app->share(function () use($app) {
    return new \Application\Translator($app);
});
/*** Application Mailer ***/
$app['application.mailer'] = $app->share(function () use($app) {
    return new \Application\Mailer($app);
});
/***** Doctrine Database & Doctrine ORM *****/
if (isset($app['databaseOptions']) && is_array($app['databaseOptions'])) {
    $app->register(new Silex\Provider\DoctrineServiceProvider(), array('dbs.options' => $app['databaseOptions']));
    $app->register(new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array('orm.em.options' => array('mappings' => array(array('type' => 'annotation', 'namespace' => 'Application\\Entity', 'path' => SRC_DIR . '/Application/Entity', 'use_simple_annotation_reader' => false))), 'orm.custom.functions.string' => array('cast' => 'Oro\\ORM\\Query\\AST\\Functions\\Cast', 'group_concat' => 'Oro\\ORM\\Query\\AST\\Functions\\String\\GroupConcat'), 'orm.custom.functions.datetime' => array('date' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'time' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'timestamp' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'convert_tz' => 'Oro\\ORM\\Query\\AST\\Functions\\DateTime\\ConvertTz'), 'orm.custom.functions.numeric' => array('timestampdiff' => 'Oro\\ORM\\Query\\AST\\Functions\\Numeric\\TimestampDiff', 'dayofyear' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'dayofweek' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'week' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'day' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'hour' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'minute' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'month' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'quarter' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'second' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'year' => 'Oro\\ORM\\Query\\AST\\Functions\\SimpleFunction', 'sign' => 'Oro\\ORM\\Query\\AST\\Functions\\Numeric\\Sign', 'pow' => 'Oro\\ORM\\Query\\AST\\Functions\\Numeric\\Pow')));
    \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array(require VENDOR_DIR . '/autoload.php', 'loadClass'));
    $entityManagerConfig = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(APP_DIR . '/src/Application/Entity'), $app['debug']);
    $entityManager = Doctrine\ORM\EntityManager::create($app['dbs.options']['default'], $entityManagerConfig);
    Doctrine\Common\Persistence\PersistentObject::setObjectManager($entityManager);
    $app['orm.proxies_dir'] = STORAGE_DIR . '/cache/proxy';
    $app['orm.manager_registry'] = $app->share(function ($app) {
        return new \Application\Doctrine\ORM\DoctrineManagerRegistry('manager_registry', array('default' => $app['orm.em']->getConnection()), array('default' => $app['orm.em']));
    });
    $app['form.extensions'] = $app->share($app->extend('form.extensions', function ($extensions) use($app) {
        $extensions[] = new \Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension($app['orm.manager_registry']);
        return $extensions;
    }));
}
/***** Validator *****/
$app->register(new \Silex\Provider\ValidatorServiceProvider());
$app['validator.mapping.mapping.file_path'] = APP_DIR . '/configs/validation.yml';
$app['validator.mapping.class_metadata_factory'] = $app->share(function ($app) {
    return new Symfony\Component\Validator\Mapping\ClassMetadataFactory(new Symfony\Component\Validator\Mapping\Loader\YamlFileLoader(APP_DIR . '/configs/validation.yml'));
Example #14
0
 public function register(Pimple\Container $c)
 {
     include __DIR__ . '/../local/config.php';
     foreach ($env as $envk => $envval) {
         $c["config/{$envk}"] = $envval;
     }
     $c['routes'] = ['/' => 'route/index', '/test', '/index', '/form', '/exception'];
     $c['entityManager'] = function ($c) {
         $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/orm"), $c['config/devVersion']);
         $conn = $c['config/databases']['default'];
         return Doctrine\ORM\EntityManager::create($conn, $config);
     };
     $c['dispatcher'] = function ($c) {
         $routes = $c['routes'];
         $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use($routes) {
             foreach ($routes as $k => $v) {
                 if (is_int($k)) {
                     $k = $v;
                     $v = "route{$v}";
                 }
                 $r->addRoute('*', $k, $v);
             }
         });
         return $dispatcher;
     };
     $c['request'] = function ($c) {
         $req = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);
         $c['logger']->notice('Started ' . $req->getMethod() . ' ' . $req->getUri()->getPath());
         return $req;
     };
     $c['resource'] = function ($c) {
         $dispatcher = $c['dispatcher'];
         $request = $c['request'];
         $uri = $request->getUri();
         $path = $uri->getPath();
         if (preg_match("|^(.+)\\..+\$|", $path, $matches)) {
             //if path ends in .json, .html, etc, ignore it
             $path = $matches[1];
         }
         $res = $dispatcher->dispatch('*', $path);
         if ($res[0] == FastRoute\Dispatcher::NOT_FOUND) {
             throw new WebAppRouteNotFoundException("Route '{$path}' not found on routing table");
         }
         $reqParameters = $res[2];
         $c['requestParameters'] = $reqParameters;
         $entry = $res[1];
         if (!isset($c[$entry])) {
             throw new WebAppResourceNotFoundException("Resource '{$entry}' not found on DI container");
         }
         $res = $c[$entry];
         $c['logger']->notice("Resource Selected ({$entry}): " . get_class($res));
         return $res;
     };
     $c['response'] = function ($c) {
         try {
             $resource = $c['resource'];
             return $resource->exec();
         } catch (Exception $e) {
             return $c['handleException']($e);
         }
     };
     $c['templaterFactory'] = function ($c) {
         $temp = new ExampleApp\templater\SampleTemplaterFactory();
         $temp->globalContext = ['url' => $c['config/publicUrl'], 'assetsUrl' => $c['config/assetsUrl']];
         return $temp;
     };
     $c['responseFactory'] = function ($c) {
         $respFactory = new Resourceful\ResponseFactory();
         $respFactory->templaterFactory = $c['templaterFactory'];
         return $respFactory;
     };
     $c['responseEmitter'] = function ($c) {
         return new Zend\Diactoros\Response\SapiEmitter();
     };
     $c['session'] = function ($c) {
         $sess = new Resourceful\SessionStorage("ExampleApp");
         $sess->startSession();
         return $sess;
     };
     $c['logger'] = function ($c) {
         $handler = new Monolog\Handler\ErrorLogHandler(Monolog\Handler\ErrorLogHandler::SAPI, Monolog\Logger::NOTICE);
         $formatter = new Monolog\Formatter\LineFormatter();
         $formatter->includeStacktraces(true);
         $handler->setFormatter($formatter);
         $log = new Monolog\Logger('webapp');
         $log->pushHandler($handler);
         return $log;
     };
     $c['handleException'] = $c->protect(function ($e) use($c) {
         $c['logger']->error($e);
         $exceptionBuilder = new \Resourceful\Exception\ExceptionResponseBuilder();
         $exceptionBuilder->includeStackTrace = $c['config/devVersion'];
         $exceptionBuilder->responseFactory = $c['responseFactory'];
         $request = null;
         try {
             $request = $c['request'];
         } catch (Exception $e) {
             //ignore and just use a null request
         }
         $resp = $exceptionBuilder->buildResponse($e, $request);
         return $resp;
     });
     $mkres = function ($cls) use($c) {
         return function ($c) use($cls) {
             $res = new $cls();
             $res->request = $c['request'];
             $res->parameters = $c['requestParameters'];
             $res->responseFactory = $c['responseFactory'];
             $res->session = $c['session'];
             return $res;
         };
     };
     $c['route/index'] = $mkres('ExampleApp\\Home\\Control\\IndexResource');
     $c['route/form'] = $mkres('ExampleApp\\Home\\Control\\FormResource');
     $c['route/exception'] = $mkres('ExampleApp\\Home\\Control\\ExceptionResource');
 }
Example #15
0
 /**
  * Get Doctrine2
  *
  * @param string $db The database instance to get (if using multiple databases)
  * @return Doctrine\ORM\EntityManager
  */
 public function getDoctrine2($db = 'default')
 {
     if ($this->_doctrine2 === null || !isset($this->_doctrine2[$db])) {
         // Get Doctrine configuration options from the application.ini file
         $dconfig = $this->getOptions();
         if ($db != 'default') {
             $dconfig = $dconfig[$db];
         }
         try {
             if (Zend_Registry::isRegistered('d2cache')) {
                 $cache = Zend_Registry::get('d2cache');
             } else {
                 $d2cacheOptions = $this->getBootstrap()->getApplication()->getOptions()['resources']['doctrine2cache'];
                 if (!$d2cacheOptions || !isset($d2cacheOptions['type'])) {
                     throw new Zend_Exception('force err');
                 }
                 $plugin = new OSS_Resource_Doctrine2cache($d2cacheOptions);
                 $this->getBootstrap()->registerPluginResource($plugin);
                 $cache = $plugin->getDoctrine2cache();
             }
         } catch (Zend_Exception $e) {
             die(_('ERROR: Doctrine2 requires Doctrine2Cache to have been already bootstrapped'));
         }
         $config = new Doctrine\ORM\Configuration();
         $config->setMetadataCacheImpl($cache);
         $driver = new \Doctrine\ORM\Mapping\Driver\XmlDriver(array($dconfig['xml_schema_path']));
         $config->setMetadataDriverImpl($driver);
         $config->setQueryCacheImpl($cache);
         $config->setResultCacheImpl($cache);
         $config->setProxyDir($dconfig['proxies_path']);
         $config->setProxyNamespace($dconfig['proxies_namespace']);
         $config->setAutoGenerateProxyClasses($dconfig['autogen_proxies']);
         if (isset($dconfig['logger']) && $dconfig['logger']) {
             $config->setSQLLogger(new OSS_Doctrine2_FirebugProfiler());
         }
         $this->_doctrine2[$db] = Doctrine\ORM\EntityManager::create($dconfig['connection']['options'], $config);
         $modelAutoLoader = new \Doctrine\Common\ClassLoader($dconfig['models_namespace'], realpath($dconfig['models_path']));
         $repositoryAutoLoader = new \Doctrine\Common\ClassLoader($dconfig['repositories_namespace'], realpath($dconfig['repositories_path']));
         $autoloader = Zend_Loader_Autoloader::getInstance();
         $autoloader->pushAutoloader(array($modelAutoLoader, 'loadClass'), $dconfig['models_namespace']);
         $autoloader->pushAutoloader(array($repositoryAutoLoader, 'loadClass'), $dconfig['repositories_namespace']);
         // http://docs.doctrine-project.org/en/latest/reference/configuration.html#autoloading-proxies
         Doctrine\ORM\Proxy\Autoloader::register($dconfig['proxies_path'], $dconfig['proxies_namespace']);
     }
     return $this->_doctrine2[$db];
 }
Example #16
0
//$loggableListener = new Gedmo\Loggable\LoggableListener;
//$loggableListener->setAnnotationReader($cachedAnnotationReader);
//$loggableListener->setUsername('admin');
//$evm->addEventSubscriber($loggableListener);
// timestampable
$timestampableListener = new Gedmo\Timestampable\TimestampableListener();
$timestampableListener->setAnnotationReader($cachedAnnotationReader);
$evm->addEventSubscriber($timestampableListener);
// blameable
$blameableListener = new \Gedmo\Blameable\BlameableListener();
$blameableListener->setAnnotationReader($cachedAnnotationReader);
$blameableListener->setUserValue('MyUsername');
// determine from your environment
$evm->addEventSubscriber($blameableListener);
// translatable
$translatableListener = new Gedmo\Translatable\TranslatableListener();
// current translation locale should be set from session or hook later into the listener
// most important, before entity manager is flushed
$translatableListener->setTranslatableLocale('en');
$translatableListener->setDefaultLocale('en');
$translatableListener->setAnnotationReader($cachedAnnotationReader);
$evm->addEventSubscriber($translatableListener);
// sortable, not used in example
//$sortableListener = new Gedmo\Sortable\SortableListener;
//$sortableListener->setAnnotationReader($cachedAnnotationReader);
//$evm->addEventSubscriber($sortableListener);
// mysql set names UTF-8 if required
$evm->addEventSubscriber(new Doctrine\DBAL\Event\Listeners\MysqlSessionInit());
// Finally, create entity manager
return Doctrine\ORM\EntityManager::create($connection, $config, $evm);
Example #17
0
    } else {
        $HT = (require PATH_BASEDIR . 'src/hardcodedtextcats/de.php');
    }
}
HardcodedText::init($HT);
$serviceManager->setFactory('db', function () {
    return null;
});
if (!HelperConfig::$core['maintenancemode']) {
    // ----------------------------------------------------------------------------
    // Begin database init
    // ----------------------------------------------------------------------------
    $serviceManager->setFactory('entitymanager', function () {
        $doctrineconfig = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration([PATH_BASEDIR . "/src"], HelperConfig::$core['debug']);
        $connectionParams = ['url' => HelperConfig::$secrets['db_type'] . '://' . HelperConfig::$secrets['db_user'] . ':' . HelperConfig::$secrets['db_password'] . '@' . HelperConfig::$secrets['db_server'] . '/' . HelperConfig::$secrets['db_name'], 'charset' => 'UTF8', 'driverOptions' => [\PDO::ATTR_EMULATE_PREPARES => false, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]];
        return Doctrine\ORM\EntityManager::create($connectionParams, $doctrineconfig);
    });
    $serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
        return $serviceManager->get('entitymanager')->getConnection()->getWrappedConnection();
    });
    // ----------------------------------------------------------------------------
    // more init stuff
    // ----------------------------------------------------------------------------
    $serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
        $langavailable = HelperConfig::$core["lang_available"];
        $textcats = new \HaaseIT\Textcat(HelperConfig::$lang, $serviceManager->get('db'), key($langavailable), HelperConfig::$core['textcatsverbose'], PATH_LOGS);
        $textcats->loadTextcats();
        return $textcats;
    });
    HelperConfig::loadNavigation($serviceManager);
}