MediaWiki  master
ObjectCache.php
Go to the documentation of this file.
1 <?php
26 
80 class ObjectCache {
82  public static $instances = [];
84  public static $wanInstances = [];
85 
92  public static function getInstance( $id ) {
93  if ( !isset( self::$instances[$id] ) ) {
94  self::$instances[$id] = self::newFromId( $id );
95  }
96 
97  return self::$instances[$id];
98  }
99 
107  public static function getWANInstance( $id ) {
108  if ( !isset( self::$wanInstances[$id] ) ) {
109  self::$wanInstances[$id] = self::newWANCacheFromId( $id );
110  }
111 
112  return self::$wanInstances[$id];
113  }
114 
122  public static function newFromId( $id ) {
123  global $wgObjectCaches;
124 
125  if ( !isset( $wgObjectCaches[$id] ) ) {
126  // Always recognize these ones
127  if ( $id === CACHE_NONE ) {
128  return new EmptyBagOStuff();
129  } elseif ( $id === 'hash' ) {
130  return new HashBagOStuff();
131  }
132 
133  throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
134  "It is not present in \$wgObjectCaches." );
135  }
136 
137  return self::newFromParams( $wgObjectCaches[$id] );
138  }
139 
149  public static function getDefaultKeyspace() {
150  global $wgCachePrefix;
151 
152  $keyspace = $wgCachePrefix;
153  if ( is_string( $keyspace ) && $keyspace !== '' ) {
154  return $keyspace;
155  }
156 
157  return WikiMap::getCurrentWikiDbDomain()->getId();
158  }
159 
171  public static function newFromParams( $params ) {
172  $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
173  if ( !isset( $params['keyspace'] ) ) {
174  $params['keyspace'] = self::getDefaultKeyspace();
175  }
176  if ( isset( $params['factory'] ) ) {
177  return call_user_func( $params['factory'], $params );
178  } elseif ( isset( $params['class'] ) ) {
179  $class = $params['class'];
180  // Automatically set the 'async' update handler
181  $params['asyncHandler'] = $params['asyncHandler'] ?? 'DeferredUpdates::addCallableUpdate';
182  // Enable reportDupes by default
183  $params['reportDupes'] = $params['reportDupes'] ?? true;
184  // Do b/c logic for SqlBagOStuff
185  if ( is_a( $class, SqlBagOStuff::class, true ) ) {
186  if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
187  $params['servers'] = [ $params['server'] ];
188  unset( $params['server'] );
189  }
190  // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
191  if ( isset( $params['servers'] ) ) {
192  foreach ( $params['servers'] as &$server ) {
193  if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
194  $server['dbDirectory'] = MediaWikiServices::getInstance()
195  ->getMainConfig()->get( 'SQLiteDataDir' );
196  }
197  }
198  }
199  }
200 
201  // Do b/c logic for MemcachedBagOStuff
202  if ( is_subclass_of( $class, MemcachedBagOStuff::class ) ) {
203  if ( !isset( $params['servers'] ) ) {
204  $params['servers'] = $GLOBALS['wgMemCachedServers'];
205  }
206  if ( !isset( $params['debug'] ) ) {
207  $params['debug'] = $GLOBALS['wgMemCachedDebug'];
208  }
209  if ( !isset( $params['persistent'] ) ) {
210  $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
211  }
212  if ( !isset( $params['timeout'] ) ) {
213  $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
214  }
215  }
216  return new $class( $params );
217  } else {
218  throw new InvalidArgumentException( "The definition of cache type \""
219  . print_r( $params, true ) . "\" lacks both "
220  . "factory and class parameters." );
221  }
222  }
223 
237  public static function newAnything( $params ) {
240  foreach ( $candidates as $candidate ) {
241  if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
242  $cache = self::getInstance( $candidate );
243  // CACHE_ACCEL might default to nothing if no APCu
244  // See includes/ServiceWiring.php
245  if ( !( $cache instanceof EmptyBagOStuff ) ) {
246  return $cache;
247  }
248  }
249  }
250 
251  if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
252  // The LoadBalancer is disabled, probably because
253  // MediaWikiServices::disableStorageBackend was called.
254  $candidate = CACHE_NONE;
255  } else {
256  $candidate = CACHE_DB;
257  }
258 
259  return self::getInstance( $candidate );
260  }
261 
279  public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
280  $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
281  if ( $cache instanceof EmptyBagOStuff ) {
282  if ( is_array( $fallback ) ) {
283  $fallback = $fallback['fallback'] ?? CACHE_NONE;
284  }
285  $cache = self::getInstance( $fallback );
286  }
287 
288  return $cache;
289  }
290 
299  public static function newWANCacheFromId( $id ) {
301 
302  if ( !isset( $wgWANObjectCaches[$id] ) ) {
303  throw new UnexpectedValueException(
304  "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
305  }
306 
307  $params = $wgWANObjectCaches[$id];
308  if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
309  throw new UnexpectedValueException(
310  "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
311  }
312  $params['store'] = $wgObjectCaches[$params['cacheId']];
313 
314  return self::newWANCacheFromParams( $params );
315  }
316 
325  public static function newWANCacheFromParams( array $params ) {
327 
328  $services = MediaWikiServices::getInstance();
329  $params['cache'] = self::newFromParams( $params['store'] );
330  $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
331  if ( !$wgCommandLineMode ) {
332  // Send the statsd data post-send on HTTP requests; avoid in CLI mode (T181385)
333  $params['stats'] = $services->getStatsdDataFactory();
334  // Let pre-emptive refreshes happen post-send on HTTP requests
335  $params['asyncHandler'] = [ DeferredUpdates::class, 'addCallableUpdate' ];
336  }
337  $params['secret'] = $params['secret'] ?? $wgSecretKey;
338  $class = $params['class'];
339 
340  return new $class( $params );
341  }
342 
349  public static function getLocalClusterInstance() {
350  global $wgMainCacheType;
351 
352  return self::getInstance( $wgMainCacheType );
353  }
354 
362  public static function getMainWANInstance() {
363  wfDeprecated( __METHOD__, '1.28' );
364  return MediaWikiServices::getInstance()->getMainWANObjectCache();
365  }
366 
374  public static function getMainStashInstance() {
375  wfDeprecated( __METHOD__, '1.28' );
376  return MediaWikiServices::getInstance()->getMainObjectStash();
377  }
378 
382  public static function clear() {
383  self::$instances = [];
384  self::$wanInstances = [];
385  }
386 
393  public static function detectLocalServerCache() {
394  if ( function_exists( 'apcu_fetch' ) ) {
395  return 'apcu';
396  } elseif ( function_exists( 'apc_fetch' ) ) {
397  return 'apc';
398  } elseif ( function_exists( 'wincache_ucache_get' ) ) {
399  return 'wincache';
400  }
401  return CACHE_NONE;
402  }
403 }
static getMainWANInstance()
Get the main WAN cache object.
CACHE_MEMCACHED $wgMainCacheType
Definition: memcached.txt:63
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static newAnything( $params)
Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
$wgSecretKey
This should always be customised in LocalSettings.php.
static newWANCacheFromParams(array $params)
Create a new cache object of the specified type.
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:92
static getLocalClusterInstance()
Get the main cluster-local cache object.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static getMainStashInstance()
Get the cache object for the main stash.
$wgWANObjectCaches
Advanced WAN object cache configuration.
static getWANInstance( $id)
Get a cached instance of the specified type of WAN cache object.
static BagOStuff [] $instances
Map of (id => BagOStuff)
Definition: ObjectCache.php:82
$wgParserCacheType
The cache type for storing article HTML.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2198
$wgMessageCacheType
The cache type for storing the contents of the MediaWiki namespace.
$cache
Definition: mcc.php:33
$params
$wgCachePrefix
Overwrite the caching key prefix with custom value.
static getDefaultKeyspace()
Get the default keyspace for this wiki.
$GLOBALS['IP']
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static WANObjectCache [] $wanInstances
Map of (id => WANObjectCache)
Definition: ObjectCache.php:84
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$fallback
Definition: MessagesAb.php:11
static newFromParams( $params)
Create a new cache object from parameters.
static newWANCacheFromId( $id)
Create a new cache object of the specified type.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
global $wgCommandLineMode
static newFromId( $id)
Create a new cache object of the specified type.
const CACHE_ANYTHING
Definition: Defines.php:97
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
$wgObjectCaches
Advanced object cache configuration.
static clear()
Clear all the cached instances.
static detectLocalServerCache()
Detects which local server cache library is present and returns a configuration for it...
const CACHE_NONE
Definition: Defines.php:98
const CACHE_DB
Definition: Defines.php:99