MemoizedCallable.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. * http://www.gnu.org/copyleft/gpl.html
  17. *
  18. * @file
  19. * @author Ori Livneh
  20. */
  21. /**
  22. * APC-backed and APCu-backed function memoization
  23. *
  24. * This class provides memoization for pure functions. A function is pure
  25. * if its result value depends on nothing other than its input parameters
  26. * and if invoking it does not cause any side-effects.
  27. *
  28. * The first invocation of the memoized callable with a particular set of
  29. * arguments will be delegated to the underlying callable. Repeat invocations
  30. * with the same input parameters will be served from APC or APCu.
  31. *
  32. * @par Example:
  33. * @code
  34. * $memoizedStrrev = new MemoizedCallable( 'range' );
  35. * $memoizedStrrev->invoke( 5, 8 ); // result: array( 5, 6, 7, 8 )
  36. * $memoizedStrrev->invokeArgs( array( 5, 8 ) ); // same
  37. * MemoizedCallable::call( 'range', array( 5, 8 ) ); // same
  38. * @endcode
  39. *
  40. * @since 1.27
  41. */
  42. class MemoizedCallable {
  43. /** @var callable */
  44. private $callable;
  45. /** @var string Unique name of callable; used for cache keys. */
  46. private $callableName;
  47. /** @var int */
  48. private $ttl;
  49. /**
  50. * @throws InvalidArgumentException if $callable is not a callable.
  51. * @param callable $callable Function or method to memoize.
  52. * @param int $ttl TTL in seconds. Defaults to 3600 (1hr). Capped at 86400 (24h).
  53. */
  54. public function __construct( $callable, $ttl = 3600 ) {
  55. if ( !is_callable( $callable, false, $this->callableName ) ) {
  56. throw new InvalidArgumentException(
  57. 'Argument 1 passed to MemoizedCallable::__construct() must ' .
  58. 'be an instance of callable; ' . gettype( $callable ) . ' given'
  59. );
  60. }
  61. if ( $this->callableName === 'Closure::__invoke' ) {
  62. // Differentiate anonymous functions from one another
  63. $this->callableName .= uniqid();
  64. }
  65. $this->callable = $callable;
  66. $this->ttl = min( max( $ttl, 1 ), 86400 );
  67. }
  68. /**
  69. * Fetch the result of a previous invocation from APC or APCu.
  70. *
  71. * @param string $key
  72. * @param bool &$success
  73. * @return bool
  74. */
  75. protected function fetchResult( $key, &$success ) {
  76. $success = false;
  77. if ( function_exists( 'apc_fetch' ) ) {
  78. return apc_fetch( $key, $success );
  79. } elseif ( function_exists( 'apcu_fetch' ) ) {
  80. return apcu_fetch( $key, $success );
  81. }
  82. return false;
  83. }
  84. /**
  85. * Store the result of an invocation in APC or APCu.
  86. *
  87. * @param string $key
  88. * @param mixed $result
  89. */
  90. protected function storeResult( $key, $result ) {
  91. if ( function_exists( 'apc_store' ) ) {
  92. apc_store( $key, $result, $this->ttl );
  93. } elseif ( function_exists( 'apcu_store' ) ) {
  94. apcu_store( $key, $result, $this->ttl );
  95. }
  96. }
  97. /**
  98. * Invoke the memoized function or method.
  99. *
  100. * @throws InvalidArgumentException If parameters list contains non-scalar items.
  101. * @param array $args Parameters for memoized function or method.
  102. * @return mixed The memoized callable's return value.
  103. */
  104. public function invokeArgs( array $args = [] ) {
  105. foreach ( $args as $arg ) {
  106. if ( $arg !== null && !is_scalar( $arg ) ) {
  107. throw new InvalidArgumentException(
  108. 'MemoizedCallable::invoke() called with non-scalar ' .
  109. 'argument'
  110. );
  111. }
  112. }
  113. $hash = md5( serialize( $args ) );
  114. $key = __CLASS__ . ':' . $this->callableName . ':' . $hash;
  115. $success = false;
  116. $result = $this->fetchResult( $key, $success );
  117. if ( !$success ) {
  118. $result = ( $this->callable )( ...$args );
  119. $this->storeResult( $key, $result );
  120. }
  121. return $result;
  122. }
  123. /**
  124. * Invoke the memoized function or method.
  125. *
  126. * Like MemoizedCallable::invokeArgs(), but variadic.
  127. *
  128. * @param mixed ...$params Parameters for memoized function or method.
  129. * @return mixed The memoized callable's return value.
  130. */
  131. public function invoke( ...$params ) {
  132. return $this->invokeArgs( $params );
  133. }
  134. /**
  135. * Shortcut method for creating a MemoizedCallable and invoking it
  136. * with the specified arguments.
  137. *
  138. * @param callable $callable
  139. * @param array $args
  140. * @param int $ttl
  141. * @return mixed
  142. */
  143. public static function call( $callable, array $args = [], $ttl = 3600 ) {
  144. $instance = new self( $callable, $ttl );
  145. return $instance->invokeArgs( $args );
  146. }
  147. }