4 use Civi\Core\Event\EventScanner
;
5 use Civi\Core\Lock\LockManager
;
6 use Symfony\Component\Config\ConfigCache
;
7 use Symfony\Component\DependencyInjection\ContainerBuilder
;
8 use Symfony\Component\DependencyInjection\Definition
;
9 use Symfony\Component\DependencyInjection\Dumper\PhpDumper
;
10 use Symfony\Component\DependencyInjection\Reference
;
11 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass
;
13 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
21 const SELF
= 'civi_container_factory';
25 * Whether to forcibly rebuild the entire container.
26 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
28 public static function singleton($reset = FALSE) {
29 if ($reset ||
!isset(\Civi
::$statics[__CLASS__
]['container'])) {
32 return \Civi
::$statics[__CLASS__
]['container'];
36 * Find a cached container definition or construct a new one.
38 * There are many weird contexts in which Civi initializes (eg different
39 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
40 * and hook_container may fire a bit differently in each context. To mitigate
41 * risk of leaks between environments, we compute a unique envID
42 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
43 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
46 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
50 * @return \Symfony\Component\DependencyInjection\ContainerInterface
52 public function loadContainer() {
53 // Note: The container's raison d'etre is to manage construction of other
54 // services. Consequently, we assume a minimal service available -- the classloader
55 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
57 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'auto';
59 // In pre-installation environments, don't bother with caching.
60 if (!defined('CIVICRM_DSN') ||
defined('CIVICRM_TEST') || CIVICRM_UF
=== 'UnitTests' ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
61 $containerBuilder = $this->createContainer();
62 $containerBuilder->compile();
63 return $containerBuilder;
66 $envId = \CRM_Core_Config_Runtime
::getId();
67 $file = \Civi
::paths()->getPath("[civicrm.compile]/CachedCiviContainer.{$envId}.php");
68 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
69 if (!$containerConfigCache->isFresh()) {
70 $containerBuilder = $this->createContainer();
71 $containerBuilder->compile();
72 $dumper = new PhpDumper($containerBuilder);
73 $containerConfigCache->write(
74 $dumper->dump(['class' => 'CachedCiviContainer']),
75 $containerBuilder->getResources()
80 $c = new \
CachedCiviContainer();
85 * Construct a new container.
87 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
88 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
90 public function createContainer() {
91 $civicrm_base_path = dirname(dirname(__DIR__
));
92 $container = new ContainerBuilder();
93 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
94 $container->addObjectResource($this);
95 $container->setParameter('civicrm_base_path', $civicrm_base_path);
96 //$container->set(self::SELF, $this);
98 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
100 $container->setDefinition(self
::SELF
, new Definition(
101 'Civi\Core\Container',
105 // TODO Move configuration to an external file; define caching structure
106 // if (empty($configDirectories)) {
107 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
109 // $locator = new FileLocator($configDirectories);
110 // $loaderResolver = new LoaderResolver(array(
111 // new YamlFileLoader($container, $locator)
113 // $delegatingLoader = new DelegatingLoader($loaderResolver);
114 // foreach (array('services.yml') as $file) {
115 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
116 // foreach ($yamlUserFiles as $file) {
117 // $delegatingLoader->load($file);
121 $container->setDefinition('angular', new Definition(
122 'Civi\Angular\Manager',
125 ->setFactory([new Reference(self
::SELF
), 'createAngularManager'])->setPublic(TRUE);
127 $container->setDefinition('angularjs.loader', new Definition('Civi\Angular\AngularLoader', []))
130 $container->setDefinition('dispatcher', new Definition(
131 'Civi\Core\CiviEventDispatcher',
134 ->setFactory([new Reference(self
::SELF
), 'createEventDispatcher'])->setPublic(TRUE);
136 $container->setDefinition('magic_function_provider', new Definition(
137 'Civi\API\Provider\MagicFunctionProvider',
141 $container->setDefinition('civi_api_kernel', new Definition(
143 [new Reference('dispatcher'), new Reference('magic_function_provider')]
145 ->setFactory([new Reference(self
::SELF
), 'createApiKernel'])->setPublic(TRUE);
147 $container->setDefinition('cxn_reg_client', new Definition(
148 'Civi\Cxn\Rpc\RegistrationClient',
151 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient')->setPublic(TRUE);
153 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []))->setPublic(TRUE);
154 $container->setDefinition('psr_log_manager', new Definition('Civi\Core\LogManager', []))->setPublic(TRUE);
155 // With the default log-manager, you may overload a channel by defining a service, e.g.
156 // $container->setDefinition('log.ipn', new Definition('CRM_Core_Error_Log', []))->setPublic(TRUE);
159 'js_strings' => 'js_strings',
160 'community_messages' => 'community_messages',
161 'checks' => 'checks',
162 'session' => 'CiviCRM Session',
164 'groups' => 'contact groups',
165 'navigation' => 'navigation',
166 'customData' => 'custom data',
167 'fields' => 'contact fields',
168 'contactTypes' => 'contactTypes',
169 'metadata' => 'metadata',
171 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
172 $definitionParams = [
174 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
176 // For Caches that we don't really care about the ttl for and/or maybe accessed
177 // fairly often we use the fastArrayDecorator which improves reads and writes, these
178 // caches should also not have concurrency risk.
179 $fastArrayCaches = ['groups', 'navigation', 'customData', 'fields', 'contactTypes', 'metadata'];
180 if (in_array($cacheSvc, $fastArrayCaches)) {
181 $definitionParams['withArray'] = 'fast';
183 $container->setDefinition("cache.{$cacheSvc}", new Definition(
184 'CRM_Utils_Cache_Interface',
186 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
189 // PrevNextCache cannot use memory or array cache at the moment because the
190 // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
191 $container->setDefinition("cache.prevNextCache", new Definition(
192 'CRM_Utils_Cache_Interface',
195 'name' => 'CiviCRM Search PrevNextCache',
196 'type' => ['SqlGroup'],
199 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
201 $container->setDefinition('sql_triggers', new Definition(
202 'Civi\Core\SqlTriggers',
206 $container->setDefinition('asset_builder', new Definition(
207 'Civi\Core\AssetBuilder',
211 $container->setDefinition('themes', new Definition(
216 $container->setDefinition('bundle.bootstrap3', new Definition('CRM_Core_Resources_Bundle', ['bootstrap3']))
217 ->setFactory('CRM_Core_Resources_Common::createBootstrap3Bundle')->setPublic(TRUE);
219 $container->setDefinition('bundle.coreStyles', new Definition('CRM_Core_Resources_Bundle', ['coreStyles']))
220 ->setFactory('CRM_Core_Resources_Common::createStyleBundle')->setPublic(TRUE);
222 $container->setDefinition('bundle.coreResources', new Definition('CRM_Core_Resources_Bundle', ['coreResources']))
223 ->setFactory('CRM_Core_Resources_Common::createFullBundle')->setPublic(TRUE);
225 $container->setDefinition('pear_mail', new Definition('Mail'))
226 ->setFactory('CRM_Utils_Mail::createMailer')->setPublic(TRUE);
228 $container->setDefinition('crypto.registry', new Definition('Civi\Crypto\CryptoService'))
229 ->setFactory('Civi\Crypto\CryptoRegistry::createDefaultRegistry')->setPublic(TRUE);
231 $container->setDefinition('crypto.token', new Definition('Civi\Crypto\CryptoToken', []))
234 $container->setDefinition('crypto.jwt', new Definition('Civi\Crypto\CryptoJwt', []))
237 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
238 throw new \
RuntimeException('Cannot initialize container. Boot services are undefined.');
240 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
241 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE)->setPublic(TRUE);
244 // Expose legacy singletons as services in the container.
246 'httpClient' => 'CRM_Utils_HttpClient',
247 'cache.default' => 'CRM_Utils_Cache',
248 'i18n' => 'CRM_Core_I18n',
249 // Maybe? 'config' => 'CRM_Core_Config',
250 // Maybe? 'smarty' => 'CRM_Core_Smarty',
252 foreach ($singletons as $name => $class) {
253 $container->setDefinition($name, new Definition(
256 ->setFactory([$class, 'singleton'])->setPublic(TRUE);
258 $container->setAlias('cache.short', 'cache.default')->setPublic(TRUE);
260 $container->setDefinition('resources', new Definition(
261 'CRM_Core_Resources',
262 [new Reference('service_container')]
263 ))->setFactory([new Reference(self
::SELF
), 'createResources'])->setPublic(TRUE);
265 $container->setDefinition('resources.js_strings', new Definition(
266 'CRM_Core_Resources_Strings',
267 [new Reference('cache.js_strings')]
270 $container->setDefinition('prevnext', new Definition(
271 'CRM_Core_PrevNextCache_Interface',
272 [new Reference('service_container')]
273 ))->setFactory([new Reference(self
::SELF
), 'createPrevNextCache'])->setPublic(TRUE);
275 $container->setDefinition('prevnext.driver.sql', new Definition(
276 'CRM_Core_PrevNextCache_Sql',
280 $container->setDefinition('prevnext.driver.redis', new Definition(
281 'CRM_Core_PrevNextCache_Redis',
282 [new Reference('cache_config')]
285 $container->setDefinition('cache_config', new Definition('ArrayObject'))
286 ->setFactory([new Reference(self
::SELF
), 'createCacheConfig'])->setPublic(TRUE);
288 $container->setDefinition('civi.activity.triggers', new Definition(
289 'Civi\Core\SqlTrigger\TimestampTriggers',
290 ['civicrm_activity', 'Activity']
291 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
293 $container->setDefinition('civi.case.triggers', new Definition(
294 'Civi\Core\SqlTrigger\TimestampTriggers',
295 ['civicrm_case', 'Case']
296 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
298 $container->setDefinition('civi.case.staticTriggers', new Definition(
299 'Civi\Core\SqlTrigger\StaticTriggers',
303 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
304 'table' => 'civicrm_case_activity',
306 'event' => ['INSERT'],
307 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
310 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
311 'table' => 'civicrm_activity',
313 'event' => ['UPDATE', 'DELETE'],
314 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id IN (SELECT ca.case_id FROM civicrm_case_activity ca WHERE ca.activity_id = OLD.id);\n",
319 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
321 $container->setDefinition('civi_token_compat', new Definition(
322 'Civi\Token\TokenCompatSubscriber',
324 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
325 $container->setDefinition("crm_mailing_action_tokens", new Definition(
326 'CRM_Mailing_ActionTokens',
328 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
330 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
331 $container->setDefinition('crm_' . strtolower($comp) . '_tokens', new Definition(
332 "CRM_{$comp}_Tokens",
334 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
336 $container->setDefinition('crm_contribution_recur_tokens', new Definition(
337 'CRM_Contribute_RecurTokens',
339 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
341 $dispatcherDefn = $container->getDefinition('dispatcher');
342 foreach (\CRM_Core_DAO_AllCoreTables
::getBaoClasses() as $baoEntity => $baoClass) {
343 $listenerMap = EventScanner
::findListeners($baoClass, $baoEntity);
345 $file = (new \
ReflectionClass($baoClass))->getFileName();
346 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource($file));
347 $dispatcherDefn->addMethodCall('addListenerMap', [$baoClass, $listenerMap]);
351 \CRM_Api4_Services
::hook_container($container);
353 \CRM_Utils_Hook
::container($container);
359 * @return \Civi\Angular\Manager
361 public function createAngularManager() {
362 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
366 * @return \Symfony\Component\EventDispatcher\EventDispatcher
368 public function createEventDispatcher() {
369 // Continue building on the original dispatcher created during bootstrap.
370 /** @var CiviEventDispatcher $dispatcher */
371 $dispatcher = static::getBootService('dispatcher.boot');
373 // Sometimes, you have a generic event ('hook_pre') and wish to fire more targeted aliases ('hook_pre::MyEntity') to allow shorter subscriber lists.
374 $aliasEvent = function($eventName, $fieldName) {
375 return function($e) use ($eventName, $fieldName) {
376 \Civi
::dispatcher()->dispatch($eventName . "::" . $e->{$fieldName}, $e);
379 $aliasMethodEvent = function($eventName, $methodName) {
380 return function($e) use ($eventName, $methodName) {
381 \Civi
::dispatcher()->dispatch($eventName . "::" . $e->{$methodName}(), $e);
385 $dispatcher->addListener('civi.api4.validate', $aliasMethodEvent('civi.api4.validate', 'getEntityName'), 100);
386 $dispatcher->addListener('civi.api4.authorizeRecord', $aliasMethodEvent('civi.api4.authorizeRecord', 'getEntityName'), 100);
388 $dispatcher->addListener('civi.core.install', ['\Civi\Core\InstallationCanary', 'check']);
389 $dispatcher->addListener('civi.core.install', ['\Civi\Core\DatabaseInitializer', 'initialize']);
390 $dispatcher->addListener('civi.core.install', ['\Civi\Core\LocalizationInitializer', 'initialize']);
391 $dispatcher->addListener('hook_civicrm_post', ['\CRM_Core_Transaction', 'addPostCommit'], -1000);
392 $dispatcher->addListener('hook_civicrm_pre', $aliasEvent('hook_civicrm_pre', 'entity'), 100);
393 $dispatcher->addListener('civi.dao.preDelete', ['\CRM_Core_BAO_EntityTag', 'preDeleteOtherEntity']);
394 $dispatcher->addListener('hook_civicrm_post', $aliasEvent('hook_civicrm_post', 'entity'), 100);
395 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
396 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
397 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
398 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
399 $dispatcher->addListener('hook_civicrm_cryptoRotateKey', ['\Civi\Crypto\RotateKeys', 'rotateSmtp']);
400 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
401 // TODO We need a better code-convention for metadata about non-hook events.
402 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
403 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
404 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
405 $dispatcher->addListenerService('civi.region.render', ['angularjs.loader', 'onRegionRender']);
406 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
407 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
408 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
409 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderL10nJs']);
410 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
411 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
412 $dispatcher->addListener('hook_civicrm_alterExternUrl', ['\CRM_Utils_System', 'migrateExternUrl'], 1000);
413 // Not a BAO class so it can't implement hookInterface
414 $dispatcher->addListener('hook_civicrm_post', ['CRM_Utils_Recent', 'on_hook_civicrm_post']);
415 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findConstPermissions'], 975);
416 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCiviPermissions'], 950);
417 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCmsPermissions'], 925);
419 $dispatcher->addListener('hook_civicrm_postSave_civicrm_domain', ['\CRM_Core_BAO_Domain', 'onPostSave']);
420 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
421 'CRM_Core_LegacyErrorHandler',
424 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
425 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
426 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
427 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
428 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
429 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
435 * @return \Civi\Core\Lock\LockManager
437 public static function createLockManager() {
438 // Ideally, downstream implementers could override any definitions in
439 // the container. For now, we'll make-do with some define()s.
440 $lm = new LockManager();
442 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: ['CRM_Core_Lock', 'createScopedLock'])
443 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: ['CRM_Core_Lock', 'createScopedLock'])
444 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: ['CRM_Core_Lock', 'createCivimailLock'])
445 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: ['CRM_Core_Lock', 'createScopedLock']);
447 // Registrations may use complex resolver expressions, but (as a micro-optimization)
448 // the default factory is specified as an array.
454 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
455 * @param $magicFunctionProvider
457 * @return \Civi\API\Kernel
459 public function createApiKernel($dispatcher, $magicFunctionProvider) {
460 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
461 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
462 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
463 $dispatcher->addSubscriber($magicFunctionProvider);
464 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
465 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
466 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter([
467 \CRM_Utils_API_HTMLInputCoder
::singleton(),
468 \CRM_Utils_API_NullOutputCoder
::singleton(),
469 \CRM_Utils_API_ReloadOption
::singleton(),
470 \CRM_Utils_API_MatchOption
::singleton(),
472 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DebugSubscriber());
473 $kernel = new \Civi\API\
Kernel($dispatcher);
475 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
476 $dispatcher->addSubscriber($reflectionProvider);
478 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
481 ['create', 'get', 'delete'],
482 // Given a file ID, determine the entity+table it's attached to.
483 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
485 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
487 // Get a list of custom fields (field_name,table_name,extends)
488 'SELECT concat("custom_",fld.id) as field_name,
489 grp.table_name as table_name,
490 grp.extends as extends
491 FROM civicrm_custom_field fld
492 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
493 WHERE fld.data_type = "File"
497 $kernel->setApiProviders([
499 $magicFunctionProvider,
506 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
507 * @return \CRM_Core_Resources
509 public static function createResources($container) {
510 $sys = \CRM_Extension_System
::singleton();
511 return new \
CRM_Core_Resources(
513 new \
CRM_Core_Resources_Strings($container->get('cache.js_strings')),
514 \CRM_Core_Config
::isUpgradeMode() ?
NULL : 'resCacheCode'
519 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
520 * @return \CRM_Core_PrevNextCache_Interface
522 public static function createPrevNextCache($container) {
523 $setting = \Civi
::settings()->get('prevNextBackend');
524 if (!$setting ||
$setting === 'default') {
525 $cacheDriver = \CRM_Utils_Cache
::getCacheDriver();
526 $service = 'prevnext.driver.' . strtolower($cacheDriver);
527 return $container->has($service)
528 ?
$container->get($service)
529 : $container->get('prevnext.driver.sql');
531 return $container->get('prevnext.driver.' . $setting);
535 * @return \ArrayObject
537 public static function createCacheConfig() {
538 $driver = \CRM_Utils_Cache
::getCacheDriver();
539 $settings = \CRM_Utils_Cache
::getCacheSettings($driver);
540 $settings['driver'] = $driver;
541 return new \
ArrayObject($settings);
545 * Get a list of boot services.
547 * These are services which must be setup *before* the container can operate.
549 * @param bool $loadFromDB
550 * @throws \CRM_Core_Exception
552 public static function boot($loadFromDB) {
553 // Array(string $serviceId => object $serviceInstance).
555 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
557 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
558 $runtime->initialize($loadFromDB);
560 $bootServices['paths'] = new \Civi\Core\
Paths();
562 $bootServices['dispatcher.boot'] = new CiviEventDispatcher();
564 // Quality control: There should be no pre-boot hooks because they make it harder to understand/support/refactor.
565 // If a pre-boot hook sneaks in, we'll raise an error.
566 $bootDispatchPolicy = [
567 '/^hook_/' => 'not-ready',
568 '/^civi\./' => 'run',
570 $mainDispatchPolicy = \CRM_Core_Config
::isUpgradeMode() ? \CRM_Upgrade_DispatchPolicy
::get('upgrade.main') : NULL;
571 $bootServices['dispatcher.boot']->setDispatchPolicy($bootDispatchPolicy);
573 $class = $runtime->userFrameworkClass
;
574 $bootServices['userSystem'] = $userSystem = new $class();
575 $userSystem->initialize();
577 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
578 $bootServices['userPermissionClass'] = new $userPermissionClass();
580 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create([
581 'name' => 'settings',
582 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
585 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
587 $bootServices['lockManager'] = self
::createLockManager();
589 if ($loadFromDB && $runtime->dsn
) {
590 \CRM_Core_DAO
::init($runtime->dsn
);
591 \CRM_Utils_Hook
::singleton(TRUE);
592 \CRM_Extension_System
::singleton(TRUE);
593 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
594 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
596 $runtime->includeCustomPath();
599 $container = $c->loadContainer();
600 foreach ($bootServices as $name => $obj) {
601 $container->set($name, $obj);
603 \Civi
::$statics[__CLASS__
]['container'] = $container;
604 // Ensure all container-based serivces have a chance to add their listeners.
605 // Without this, it's a matter of happenstance (dependent upon particular page-request/configuration/etc).
606 $container->get('dispatcher');
610 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
615 * @param string $name
619 public static function getBootService($name) {
620 return \Civi
::$statics[__CLASS__
]['boot'][$name];
624 * Determine whether the container services are available.
628 public static function isContainerBooted() {
629 return isset(\Civi
::$statics[__CLASS__
]['container']);