MediaWiki master
MemoizedCallable.php
Go to the documentation of this file.
1<?php
31
33 private $callable;
34
36 private $callableName;
37
39 private $ttl;
40
48 public function __construct( $callable, $ttl = 3600 ) {
49 if ( !is_callable( $callable, false, $this->callableName ) ) {
50 throw new InvalidArgumentException(
51 'Argument 1 passed to MemoizedCallable::__construct() must ' .
52 'be a callable; ' . get_debug_type( $callable ) . ' given'
53 );
54 }
55
56 if ( $callable instanceof Closure ) {
57 throw new InvalidArgumentException( 'Cannot memoize unnamed closure' );
58 }
59
60 if ( is_object( $callable ) || is_object( $callable[ 0 ] ) ) {
61 throw new InvalidArgumentException( 'Cannot memoize object-bound callable' );
62 }
63
64 $this->callable = $callable;
65 $this->ttl = min( max( $ttl, 1 ), 86400 );
66 }
67
75 protected function fetchResult( $key, &$success ) {
76 $success = false;
77 if ( function_exists( 'apcu_fetch' ) ) {
78 return apcu_fetch( $key, $success );
79 }
80 return false;
81 }
82
89 protected function storeResult( $key, $result ) {
90 if ( function_exists( 'apcu_store' ) ) {
91 apcu_store( $key, $result, $this->ttl );
92 }
93 }
94
102 public function invokeArgs( array $args = [] ) {
103 foreach ( $args as $arg ) {
104 if ( $arg !== null && !is_scalar( $arg ) ) {
105 throw new InvalidArgumentException(
106 'MemoizedCallable::invoke() called with non-scalar ' .
107 'argument'
108 );
109 }
110 }
111
112 $hash = md5( serialize( $args ) );
113 $key = __CLASS__ . ':' . $this->callableName . ':' . $hash;
114 $success = false;
115 $result = $this->fetchResult( $key, $success );
116 if ( !$success ) {
117 $result = ( $this->callable )( ...$args );
118 $this->storeResult( $key, $result );
119 }
120
121 return $result;
122 }
123
132 public function invoke( ...$params ) {
133 return $this->invokeArgs( $params );
134 }
135
145 public static function call( $callable, array $args = [], $ttl = 3600 ) {
146 $instance = new self( $callable, $ttl );
147 return $instance->invokeArgs( $args );
148 }
149}
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.
invokeArgs(array $args=[])
Invoke the memoized function or method.
storeResult( $key, $result)
Store the result of an invocation.