title: Best way to implement a decorator pattern for method result caching in PHP
body: <p>I have a set of classes which have a habit of being called repeatedly with the same arguments. These methods generally run database requests and build arrays of objects and such, and so to cut out this duplication I've constructed a couple of caching methods to optimise. These are used like so:</p>
  
  <p>Before caching applied:</p>
  
  <pre><code>public function method($arg1, $arg2) {
  $result = doWork();
  return $result;
  }
  </code></pre>
  
  <p>After caching applied:</p>
  
  <pre><code>public function method($arg1, $arg2, $useCached=true) {
  if ($useCached) {return $this-&gt;tryCache();}
  $result = doWork();
  return $this-&gt;cache($result);
  }
  </code></pre>
  
  <p>Unfortunately I'm now left with the slightly laborious task of manually adding this to all of the methods- I believe this is a use case of the decorator pattern but I can't figure out how to implement it in a simpler way in PHP for this case.</p>
  
  <p>What's the best way to do this, hopefully such that either <em>all</em> methods in any of these classes automatically do this, or I just have to add one line in the method etc?</p>
  
  <p>I've had a look at ways to override the return statement and such but can't really see anything.</p>
  
  <p>Thanks!</p>