title: Using json_encode to temporarily store Resources from the YouTube Data API
body: <p>I've been working on a custom WordPress plugin for integrating YouTube content into a gaming blog, and in order to limit the strain on the daily API quota, I've been trying to come up with a way to store temporary cache objects which expire after 24 hours.</p>
  
  <p>I created the following class to manage the data:</p>
  
  <pre><code>public class YouTubeDataCache {
      protected $dataObject;
      protected $expirationDate;
  
      __construct($dataObject) {
          $this-&gt;dataObject = $dataObject;
          $this-&gt;expirationDate = time() + 86400;
      }
  
      public function isExpired() {
          return $this-&gt;expirationDate &lt; time();
      }
  
      public function getDataObject() {
          return $this-&gt;dataObject;
      }
  }
  </code></pre>
  
  <p>And then, I call <code>json_encode($dataCache)</code> on instances of this class to generate a JSON representation of the instance that I can store in the DB.</p>
  
  <p>Once I started testing this, though, I noticed two significant problems:</p>
  
  <ol>
  <li>The database entries were blank despite verifyin that Google's API returned actual results.</li>
  <li>calling <code>json_decode()</code> on the strings pulled <em>out</em> of the database returned fatal errors for undefined methods when I tried calling <code>isExpired()</code> on the decoded object.</li>
  </ol>
  
  <p>My question is two-fold:</p>
  
  <ol>
  <li>How can I make sure that all the necessary data elements get encoded into the JSON string?</li>
  <li>How can I retain access to the object's methods after calling <code>json_decode()</code>?</li>
  </ol>