MediaWiki REL1_34
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 // Differentiate anonymous functions from one another
69 $this->callableName .= uniqid();
70 }
71
72 $this->callable = $callable;
73 $this->ttl = min( max( $ttl, 1 ), 86400 );
74 }
75
83 protected function fetchResult( $key, &$success ) {
84 $success = false;
85 if ( function_exists( 'apc_fetch' ) ) {
86 return apc_fetch( $key, $success );
87 } elseif ( function_exists( 'apcu_fetch' ) ) {
88 return apcu_fetch( $key, $success );
89 }
90 return false;
91 }
92
99 protected function storeResult( $key, $result ) {
100 if ( function_exists( 'apc_store' ) ) {
101 apc_store( $key, $result, $this->ttl );
102 } elseif ( function_exists( 'apcu_store' ) ) {
103 apcu_store( $key, $result, $this->ttl );
104 }
105 }
106
114 public function invokeArgs( array $args = [] ) {
115 foreach ( $args as $arg ) {
116 if ( $arg !== null && !is_scalar( $arg ) ) {
117 throw new InvalidArgumentException(
118 'MemoizedCallable::invoke() called with non-scalar ' .
119 'argument'
120 );
121 }
122 }
123
124 $hash = md5( serialize( $args ) );
125 $key = __CLASS__ . ':' . $this->callableName . ':' . $hash;
126 $success = false;
127 $result = $this->fetchResult( $key, $success );
128 if ( !$success ) {
129 $result = ( $this->callable )( ...$args );
130 $this->storeResult( $key, $result );
131 }
132
133 return $result;
134 }
135
144 public function invoke( ...$params ) {
145 return $this->invokeArgs( $params );
146 }
147
157 public static function call( $callable, array $args = [], $ttl = 3600 ) {
158 $instance = new self( $callable, $ttl );
159 return $instance->invokeArgs( $args );
160 }
161}
serialize()
if( $line===false) $args
Definition cdb.php:64
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.