MediaWiki REL1_37
MemoizedCallable.php
Go to the documentation of this file.
1<?php
44
46 private $callable;
47
50
52 private $ttl;
53
59 public function __construct( $callable, $ttl = 3600 ) {
60 if ( !is_callable( $callable, false, $this->callableName ) ) {
61 throw new InvalidArgumentException(
62 'Argument 1 passed to MemoizedCallable::__construct() must ' .
63 'be an instance of callable; ' . gettype( $callable ) . ' given'
64 );
65 }
66
67 if ( $this->callableName === 'Closure::__invoke' ) {
68 throw new InvalidArgumentException( 'Cannot memoize unnamed closure' );
69 }
70
71 $this->callable = $callable;
72 $this->ttl = min( max( $ttl, 1 ), 86400 );
73 }
74
82 protected function fetchResult( $key, &$success ) {
83 $success = false;
84 if ( function_exists( 'apc_fetch' ) ) {
85 return apc_fetch( $key, $success );
86 } elseif ( function_exists( 'apcu_fetch' ) ) {
87 return apcu_fetch( $key, $success );
88 }
89 return false;
90 }
91
98 protected function storeResult( $key, $result ) {
99 if ( function_exists( 'apc_store' ) ) {
100 apc_store( $key, $result, $this->ttl );
101 } elseif ( function_exists( 'apcu_store' ) ) {
102 apcu_store( $key, $result, $this->ttl );
103 }
104 }
105
113 public function invokeArgs( array $args = [] ) {
114 foreach ( $args as $arg ) {
115 if ( $arg !== null && !is_scalar( $arg ) ) {
116 throw new InvalidArgumentException(
117 'MemoizedCallable::invoke() called with non-scalar ' .
118 'argument'
119 );
120 }
121 }
122
123 $hash = md5( serialize( $args ) );
124 $key = __CLASS__ . ':' . $this->callableName . ':' . $hash;
125 $success = false;
126 $result = $this->fetchResult( $key, $success );
127 if ( !$success ) {
128 $result = ( $this->callable )( ...$args );
129 $this->storeResult( $key, $result );
130 }
131
132 return $result;
133 }
134
143 public function invoke( ...$params ) {
144 return $this->invokeArgs( $params );
145 }
146
156 public static function call( $callable, array $args = [], $ttl = 3600 ) {
157 $instance = new self( $callable, $ttl );
158 return $instance->invokeArgs( $args );
159 }
160}
serialize()
APC-backed and APCu-backed function memoization.
static call( $callable, array $args=[], $ttl=3600)
Shortcut method for creating a MemoizedCallable and invoking it with the specified arguments.
invoke(... $params)
Invoke the memoized function or method.
__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.
if( $line===false) $args
Definition mcc.php:124