MediaWiki REL1_31
MemoizedCallable.php
Go to the documentation of this file.
1<?php
44
46 private $callable;
47
50
56 public function __construct( $callable, $ttl = 3600 ) {
57 if ( !is_callable( $callable, false, $this->callableName ) ) {
58 throw new InvalidArgumentException(
59 'Argument 1 passed to MemoizedCallable::__construct() must ' .
60 'be an instance of callable; ' . gettype( $callable ) . ' given'
61 );
62 }
63
64 if ( $this->callableName === 'Closure::__invoke' ) {
65 // Differentiate anonymous functions from one another
66 $this->callableName .= uniqid();
67 }
68
69 $this->callable = $callable;
70 $this->ttl = min( max( $ttl, 1 ), 86400 );
71 }
72
80 protected function fetchResult( $key, &$success ) {
81 $success = false;
82 if ( function_exists( 'apc_fetch' ) ) {
83 return apc_fetch( $key, $success );
84 } elseif ( function_exists( 'apcu_fetch' ) ) {
85 return apcu_fetch( $key, $success );
86 }
87 return false;
88 }
89
96 protected function storeResult( $key, $result ) {
97 if ( function_exists( 'apc_store' ) ) {
98 apc_store( $key, $result, $this->ttl );
99 } elseif ( function_exists( 'apcu_store' ) ) {
100 apcu_store( $key, $result, $this->ttl );
101 }
102 }
103
111 public function invokeArgs( array $args = [] ) {
112 foreach ( $args as $arg ) {
113 if ( $arg !== null && !is_scalar( $arg ) ) {
114 throw new InvalidArgumentException(
115 'MemoizedCallable::invoke() called with non-scalar ' .
116 'argument'
117 );
118 }
119 }
120
121 $hash = md5( serialize( $args ) );
122 $key = __CLASS__ . ':' . $this->callableName . ':' . $hash;
123 $success = false;
124 $result = $this->fetchResult( $key, $success );
125 if ( !$success ) {
126 $result = call_user_func_array( $this->callable, $args );
127 $this->storeResult( $key, $result );
128 }
129
130 return $result;
131 }
132
141 public function invoke() {
142 return $this->invokeArgs( func_get_args() );
143 }
144
154 public static function call( $callable, array $args = [], $ttl = 3600 ) {
155 $instance = new self( $callable, $ttl );
156 return $instance->invokeArgs( $args );
157 }
158}
serialize()
if( $line===false) $args
Definition cdb.php:64
APC-backed and APCu-backed function memoization.
invoke()
Invoke the memoized function or method.
static call( $callable, array $args=[], $ttl=3600)
Shortcut method for creating a MemoizedCallable and invoking it with the specified arguments.
__construct( $callable, $ttl=3600)
fetchResult( $key, &$success)
Fetch the result of a previous invocation from APC or APCu.
string $callableName
Unique name of callable; used for cache keys.
invokeArgs(array $args=[])
Invoke the memoized function or method.
storeResult( $key, $result)
Store the result of an invocation in APC or APCu.
namespace being checked & $result
Definition hooks.txt:2323