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; }
$app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallback' => 'en_US')); $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) {
<?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();
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'); }
if (file_exists(PATH_BASEDIR . 'src/hardcodedtextcats/' . key(HelperConfig::$core["lang_available"]) . '.php')) { $HT = (require PATH_BASEDIR . 'src/hardcodedtextcats/' . key(HelperConfig::$core["lang_available"]) . '.php'); } 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; });