Civi
in package
Class Civi
The "Civi" class provides a facade for accessing major subsystems, such as the service-container and settings manager. It serves as a bridge which allows procedural code to access important objects.
General principles:
- Each function provides access to a major subsystem.
- Each function performs a simple lookup.
- Each function returns an interface.
- Whenever possible, interfaces should be well-known (e.g. based on a standard or well-regarded provider).
Table of Contents
Properties
- $statics : array<string|int, mixed>
- A central location for static variable storage.
Methods
- cache() : CRM_Utils_Cache_Interface
- Retrieve a named cache instance.
- contactSettings() : SettingsBag
- Obtain the contact's personal settings.
- container() : ContainerInterface
- Get the service container.
- dispatcher() : CiviEventDispatcherInterface
- Get the event dispatcher.
- entity() : EntityProvider
- Get the canonical entityProvider for a given entity type.
- format() : Format
- Obtain the formatting object.
- lockManager() : LockManager
- log() : LoggerInterface
- Find or create a logger.
- paths() : Paths
- Obtain the core file/path mapper.
- pipe() : void
- Initiate a bidirectional pipe for exchanging a series of multiple API requests.
- queue() : CRM_Queue_Queue
- Fetch a queue object.
- reset() : mixed
- Reset all ephemeral system state, e.g. statics, singletons, containers.
- resources() : CRM_Core_Resources
- schemaHelper() : SchemaHelperInterface
- Get the schema-helper for CiviCRM (core-core).
- service() : mixed
- Fetch a service from the container.
- settings() : SettingsBag
- Obtain the domain settings.
- table() : EntityProvider
- Get the canonical entityProvider for a given entity table.
- url() : Url
- Construct a URL based on a logical service address. For example:
Properties
$statics
A central location for static variable storage.
public
static array<string|int, mixed>
$statics
= []
`Civi::$statics[__CLASS__]['foo'] = 'bar';
Methods
cache()
Retrieve a named cache instance.
public
static cache([string $name = 'default' ]) : CRM_Utils_Cache_Interface
Parameters
- $name : string = 'default'
-
The name of the cache. The 'default' cache is biased toward high-performance caches (eg memcache/redis/apc) when available and falls back to single-request (static) caching. Ex: 'short' or 'default' is useful for high-speed, short-lived cache data. This is appropriate if you believe that latency (millisecond-level read time) is the main factor. For example: caching data from a couple SQL queries. Ex: 'long' can be useful for longer-lived cache data. It's appropriate if you believe that longevity (e.g. surviving for several hours or a day) is more important than millisecond-level access time. For example: caching the result of a simple metadata-query.
Return values
CRM_Utils_Cache_Interface —NOTE: Beginning in CiviCRM v5.4, the cache instance complies with PSR-16 (\Psr\SimpleCache\CacheInterface).
contactSettings()
Obtain the contact's personal settings.
public
static contactSettings([null|int $contactID = NULL ][, null|int $domainID = NULL ]) : SettingsBag
Parameters
- $contactID : null|int = NULL
-
For the default/active user's contact, leave $domainID as NULL.
- $domainID : null|int = NULL
-
For the default domain, leave $domainID as NULL.
Tags
Return values
SettingsBagcontainer()
Get the service container.
public
static container() : ContainerInterface
Return values
ContainerInterfacedispatcher()
Get the event dispatcher.
public
static dispatcher() : CiviEventDispatcherInterface
Return values
CiviEventDispatcherInterfaceentity()
Get the canonical entityProvider for a given entity type.
public
static entity(string $entityName) : EntityProvider
Parameters
- $entityName : string
Return values
EntityProviderformat()
Obtain the formatting object.
public
static format() : Format
Return values
FormatlockManager()
public
static lockManager() : LockManager
Return values
LockManagerlog()
Find or create a logger.
public
static log([string $channel = 'default' ]) : LoggerInterface
Parameters
- $channel : string = 'default'
-
Symbolic name (or channel) of the intended log. This should correlate to a service "log.{NAME}".
Return values
LoggerInterfacepaths()
Obtain the core file/path mapper.
public
static paths() : Paths
Return values
Pathspipe()
Initiate a bidirectional pipe for exchanging a series of multiple API requests.
public
static pipe([string $negotiationFlags = 'vtl' ]) : void
Parameters
- $negotiationFlags : string = 'vtl'
-
List of pipe initialization flags. Some combination of the following:
- 'v': Report version in connection header.
- 'j': Report JSON-RPC flavors in connection header.
- 'l': Report on login support in connection header.
- 't': Trusted session. Logins do not require credentials. API calls may execute with or without permission-checks.
- 'u': Untrusted session. Logins require credentials. API calls may only execute with permission-checks.
The
Civi::pipe()
entry-point is designed to be amenable to shell orchestration (SSH/cv/drush/wp-cli/etc). The negotiation flags are therefore condensed to individual characters.It is possible to preserve compatibility while adding new default-flags. However, removing default-flags is more likely to be a breaking-change.
When adding a new flag, consider whether mutable
option()
s may be more appropriate.
Tags
queue()
Fetch a queue object.
public
static queue(string $name[, array{type: string, is_autorun: bool, reset: bool, is_persistent: bool} $params = [] ]) : CRM_Queue_Queue
Note: Historically, CRM_Queue_Queue
objects were not persistently-registered. Persistence
is now encouraged. This facade has a bias towards persistently-registered queues.
Parameters
- $name : string
-
The name of a persistent/registered queue (stored in
civicrm_queue
) - $params : array{type: string, is_autorun: bool, reset: bool, is_persistent: bool} = []
-
Specification for a queue. This is not required for accessing an existing queue. Specify this if you wish to auto-create the queue or to include advanced options (eg
reset
). Example: ['type' => 'Sql', 'error' => 'abort'] Example: ['type' => 'SqlParallel', 'error' => 'delete'] Defaults: ['reset'=>FALSE, 'is_persistent'=>TRUE, 'is_autorun'=>FALSE]
Tags
Return values
CRM_Queue_Queuereset()
Reset all ephemeral system state, e.g. statics, singletons, containers.
public
static reset() : mixed
resources()
public
static resources() : CRM_Core_Resources
Return values
CRM_Core_ResourcesschemaHelper()
Get the schema-helper for CiviCRM (core-core).
public
static schemaHelper([string $key = 'civicrm' ]) : SchemaHelperInterface
Parameters
- $key : string = 'civicrm'
-
Ex: 'civicrm' or 'org.example.myextension'
Return values
SchemaHelperInterfaceservice()
Fetch a service from the container.
public
static service(string $id) : mixed
Parameters
- $id : string
-
The service ID.
settings()
Obtain the domain settings.
public
static settings([int|null $domainID = NULL ]) : SettingsBag
Parameters
- $domainID : int|null = NULL
-
For the default domain, leave $domainID as NULL.
Return values
SettingsBagtable()
Get the canonical entityProvider for a given entity table.
public
static table(string $tableName) : EntityProvider
Parameters
- $tableName : string
Return values
EntityProviderurl()
Construct a URL based on a logical service address. For example:
public
static url([string|null $logicalUri = NULL ][, string|null $flags = NULL ]) : Url
Civi::url('frontend://civicrm/user?reset=1');
Civi::url() ->setScheme('frontend') ->setPath(['civicrm', 'user']) ->setQuery(['reset' => 1])
URL building follows a few rules:
- You may initialize with a baseline URL.
- The scheme indicates the general type of URL ('frontend://', 'backend://', 'asset://', 'assetBuilder://').
- The result object provides getters, setters, and adders (e.g.
getScheme()
,setPath(...)
,addQuery(...)
) - Strings are raw. Arrays are auto-encoded. (
addQuery('name=John+Doughnut')
oraddQuery(['name' => 'John Doughnut'])
) - You may use variable expressions (
id=[contact]&gid=[profile]
). - The URL can be cast to string (aka
__toString()
).
If you are converting from CRM_Utils_System::url()
to Civi::url()
, then be sure to:
- Pay attention to the scheme (eg 'current://' vs 'frontend://')
- Pay attention to HTML escaping, as the behavior changed:
- Civi::url() returns plain URLs (eg "id=100&gid=200") by default
- CRM_Utils_System::url() returns HTML-escaped URLs (eg "id=100&gid=200") by default
Here are several examples:
Ex: Link to constituent's dashboard (on frontend UI or backend UI -- based on the active scheme of current page-view) $url = Civi::url('current://civicrm/user?reset=1'); $url = Civi::url('//civicrm/user?reset=1');
Ex: Link to constituent's dashboard (with method calls - good for dynamic options) $url = Civi::url('frontend:') ->setPath('civicrm/user') ->addQuery(['reset' => 1]);
Ex: Link to constituent's dashboard (with quick flags: absolute URL, SSL required, HTML escaping) $url = Civi::url('frontend://civicrm/user?reset=1', 'ash');
Ex: Link to constituent's dashboard (with method flags - good for dynamic options) $url = Civi::url('frontend://civicrm/user?reset=1') ->setPreferFormat('absolute') ->setSsl(TRUE) ->setHtmlEscape(TRUE);
Ex: Link to a dynamically generated asset-file. $url = Civi::url('assetBuilder://crm-l10n.js?locale=en_US');
Ex: Link to a static asset (resource-file) in one of core's configurable paths. $url = Civi::url('[civicrm.root]/js/Common.js');
Ex: Link to a static asset (resource-file) in an extension. $url = Civi::url('ext://org.civicrm.search_kit/css/crmSearchTasks.css');
Ex: Link with variable substitution $url = Civi::url('frontend://civicrm/ajax/api4/[entity]/[action]') ->addVars(['entity' => 'Foo', 'action' => 'bar']);
Parameters
- $logicalUri : string|null = NULL
-
Logical URI. The scheme of the URI may be one of:
- 'frontend://' (Front-end page-route for constituents)
- 'backend://' (Back-end page-route for staff)
- 'service://' (Web-service page-route for automated integrations; aka webhooks and IPNs)
- 'current://' (Whichever UI is currently active)
- 'default://' (Whichever UI is recorded in the metadata)
- 'asset://' (Static asset-file; see \Civi::paths())
- 'assetBuilder://' (Dynamically-generated asset-file; see \Civi\Core\AssetBuilder)
- 'ext://' (Static asset-file provided by an extension)
An empty scheme (
//hello.txt
) is equivalent tocurrent://hello.txt
.
- $flags : string|null = NULL
-
List of flags. Some combination of the following:
- 'a': absolute (aka
setPreferFormat('absolute')
) - 'r': relative (aka
setPreferFormat('relative')
) - 'h': html (aka
setHtmlEscape(TRUE)
) - 't': text (aka
setHtmlEscape(FALSE)
) - 's': ssl (aka
setSsl(TRUE)
) - 'c': cache code for resources (aka Civi::resources()->addCacheCode())
- 'a': absolute (aka
Return values
Url —URL object which may be modified or rendered as text.