Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Add Cache::touch() & Store::touch() for TTL Extension #55954

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
Loading
from

Conversation

yitzwillroth
Copy link
Contributor

@yitzwillroth yitzwillroth commented Jun 8, 2025

This pull request introduces the Cache::touch() method, addressing a fundamental challenge that developers encounter frequently: extending cache TTL without the overhead of retrieving and re-storing data.

Basic Usage:

// with seconds

Cache::touch('user_session:123', 3600); // extend by 1 hour

// with datetime

Cache::touch('analytics_data', now()->addHours(6));

// with carbon

Cache::touch('report_cache', Carbon::now()->addMinutes(30));

Simplifies Common Patterns:

// conditional re-caching

if (Cache::has($key)) {
    Cache::put($key, Cache::get($key), $newTtl);
}


// remember with forced refresh

Cache::forget($key);
Cache::remember($key, $ttl, $callback);


// manual ttl tracking

if ($value = Cache::get($key) && $this->shouldExtendCache($key)) {
    Cache::put($key, $value, $ttl);
}

// these all become:

Cache::touch($key, $ttl)

Cache:touch() & $store->touch() return true on success and false when the item is not found in the cache.

Cache:touch() accepts an int, DateTimeInterface, or DateInterval for extending the TTL; null will extend the TTL indefinitely; $store->touch() requires an int (conversion is handled in the Repository.

This pull request includes the following:

  • Notation on Cache Facade
  • Updated Repository and Store Contracts
  • Implementations for all Drivers - ApcStore, ArrayStore, DatabaseStore, DynamoDbStore, FileStore, MemcachedStore, MemoizedStore , NullStore, and RedisStore
  • Complete Tests

Primary Use Cases

1. Activity-Based Cache Extension

// user is actively browsing - extend their session cache

// instead of

$sessionData = Cache::get("user_session:{$user->id}");
if ($sessionData && $user->isActive()) {
    Cache::put("user_session:{$user->id}", $sessionData, 3600);
}

// now you can simply do this

if ($user->isActive()) {
    Cache::touch("user_session:{$user->id}", 3600); // Extend by 1 hour
}

2. Cache Warming Maintenance

// keep expensive computation results fresh during maintenance windows

foreach (['big_report', 'big_metrics', 'big_data'] as $key) {
    Cache::touch($key, now()->addHours(6)); // extend thru window
}

3. Progressive Cache Strategies

// extend cache for popular content

if ($post->isPopular()) {
    Cache::touch("post_content:{$post->id}", 86400); // keep popular posts cached longer
}

Real-World Scenarios

E-commerce Product Caching

// extend cache for products being actively viewed/purchased

public function extendPopularProductCache(int $productId): void
{
    if (Redis::get("product_views:{$productId}:last_hour") > 50) {
        Cache::touch("product_details:{$productId}", 7200);
        Cache::touch("product_inventory:{$productId}", 1800);
    }
}

API Response Caching

// extend cache for frequently requested api endpoints

public function handleApiRequest(string $endpoint): bool
{
    $key = "api_response:" . md5($endpoint);

    if ($this->isFrequentlyRequested($endpoint)) {
        Cache::touch($key, 7200);
    }

    return Cache::remember($key, 1800, fn() => $this->fetchApiData($endpoint));
}

Performance Benefits

Network/Storage Efficiency

  • Redis: Avoids GET + SET operations, uses single EXPIRE command
  • Database: Avoids SELECT + UPDATE, uses single UPDATE on timestamp
  • Memcached: Uses TOUCH command instead of GET + SET

Memory Efficiency

// current approach - potentially large data transfer

$largeDataset = Cache::get('analytics_data'); // 10MB transfer
Cache::put('analytics_data', $largeDataset, 3600); // 10MB transfer


// with touch() - minimal overhead

Cache::touch('analytics_data', 3600); // just updates expiration

  • Solves Real Pain: Every Laravel developer has written the inefficient get/put pattern
  • Clean API: Cache::touch($key, $seconds) is immediately understandable
  • Performance Win: Significant efficiency gains with minimal code change
  • Driver Agnostic: Works across all cache backends
  • Framework Precedent: Similar to filesystem touch() command developers know

Copy link

github-actions bot commented Jun 8, 2025

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@yitzwillroth yitzwillroth marked this pull request as ready for review June 8, 2025 18:21
@yitzwillroth yitzwillroth force-pushed the add-cache-ttl-extension branch from 52bc6b1 to 73fa810 Compare June 8, 2025 19:13
@crynobone crynobone changed the title [12.x] Add Cache::touch() & Store::touche() for TTL Extension [12.x] Add Cache::touch() & Store::touch() for TTL Extension Jun 9, 2025
@taylorotwell
Copy link
Member

This is pretty cool. One caveat though is the addition of the method to the cache repository contract which will be a breaking change to any existing implementations. For that reason we may probably need to target this to master branch.

@taylorotwell taylorotwell marked this pull request as draft June 9, 2025 14:26
@yitzwillroth yitzwillroth changed the title [12.x] Add Cache::touch() & Store::touch() for TTL Extension Add Cache::touch() & Store::touch() for TTL Extension Jun 9, 2025
@yitzwillroth yitzwillroth changed the base branch from 12.x to master June 9, 2025 14:43
@yitzwillroth yitzwillroth force-pushed the add-cache-ttl-extension branch from 73fa810 to 485efd0 Compare June 9, 2025 14:47
@yitzwillroth
Copy link
Contributor Author

@taylorotwell Done.

@yitzwillroth yitzwillroth marked this pull request as ready for review June 9, 2025 14:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.