Mini Caching in Classes

Sometimes you have a database-generated list that gets accessed multiple times within a single script execution. You don’t want to globalize the results or pass data between distant scopes. Here’s a simple solution: implement a local cache within the originating class.

The Pattern

Use a private attribute to store cached values, keyed by method name using PHP’s __METHOD__ constant:

class MyService
{
    private $cache = [];

    public function getExpensiveList()
    {
        if (isset($this->cache[__METHOD__])) {
            return $this->cache[__METHOD__];
        }

        // Expensive database query here
        $result = $this->db->fetchAll('SELECT * FROM items');

        $this->cache[__METHOD__] = $result;
        return $result;
    }
}

The logic is simple: check if a cache entry exists; if yes, return it; otherwise, generate the value, store it, and return it. This works without any additional cache tools installed.

When to Use This

This technique is useful when:

  • Data remains constant during script execution but may change between page loads
  • Results are read multiple times from different locations in your code
  • Memcached or similar systems aren’t available or would be overkill

For static, infrequently-changing data, dedicated cache systems remain preferable. And if the data rarely changes at all, consider hardcoding it as class constants instead.

Sometimes the simplest solution is the right one.