Skip to content

ObjectCacheTrait

Mostafa Soufi edited this page Sep 1, 2024 · 2 revisions

The ObjectCacheTrait is a PHP trait included in the WP-Statistics plugin to manage caching operations efficiently. It provides a standardized way to cache data, reducing redundant database queries and improving overall performance.

Features

  • Centralized Caching Logic: Provides a unified interface for caching operations within classes.
  • Easy to Use: Simple methods for setting, getting, and managing cache data.
  • Automatic Data Caching: Use a single method to cache expensive operations and avoid redundant calculations.
  • Reusable: Can be easily included in any class to implement caching functionality.

How to Use

To use the ObjectCacheTrait in your class, follow these steps:

1. Include the Trait

First, ensure the trait is available in your project and include it in your class:

<?php

namespace YourNamespace;

use WP_Statistics\Traits\ObjectCacheTrait;

class YourClass
{
    use ObjectCacheTrait;

    // Your class methods and properties
}

2. Cache Data Using getCachedData

Use the getCachedData method to cache the results of expensive operations. Provide a cache key and a callback function to retrieve the data if it’s not already cached:

public function getExpensiveData()
{
    return $this->getCachedData('expensiveDataKey', function () {
        // Your expensive operation or data fetching logic
        return $this->fetchDataFromDatabase();
    });
}

3. Manually Set and Get Cache Data

For more control, manually set and retrieve cached data using setCache and getCache:

// Set data to cache
$this->setCache('myKey', $myData);

// Get data from cache
$cachedData = $this->getCache('myKey');

4. Check if Cache is Set

Check if a specific cache key has been set using isCacheSet:

if ($this->isCacheSet('myKey')) {
    // Cache is set
} else {
    // Cache is not set
}

5. Reset the Cache

To clear all cached entries, use the resetCache method:

$this->resetCache();

Example Usage

Here’s an example of a class using ObjectCacheTrait to cache database results:

<?php

namespace YourNamespace;

use WP_Statistics\Traits\ObjectCacheTrait;

class ExampleClass
{
    use ObjectCacheTrait;

    public function getTopSellingProducts()
    {
        return $this->getCachedData('topSellingProducts', function () {
            // Simulating a database query
            return $this->fetchTopSellingProductsFromDatabase();
        });
    }

    private function fetchTopSellingProductsFromDatabase()
    {
        // Simulate database query
        return [
            ['name' => 'Product A', 'sales' => 100],
            ['name' => 'Product B', 'sales' => 90],
        ];
    }
}

Best Practices

  • Use Descriptive Cache Keys: Ensure cache keys are meaningful and unique to prevent conflicts.
  • Invalidate Cache When Necessary: Clear or reset cache when the underlying data changes to keep the cache valid.
  • Optimize Caching Strategy: Consider the data’s nature and frequency of change when implementing caching to ensure optimal performance.

Conclusion

The ObjectCacheTrait is a powerful tool for managing caching in your PHP applications. By using this trait, you can significantly improve performance by reducing redundant operations and optimizing data retrieval.

Clone this wiki locally