Shopware 6.7 introduces significant improvements to cache management and performance optimization. As developers working with this powerful e-commerce platform, understanding how to programmatically clear specific caches is crucial for maintaining optimal performance while implementing custom functionality. This guide will walk you through various methods to clear specific caches programmatically in Shopware 6.7.
Understanding Shopware 6.7 Cache Architecture
Before diving into the implementation details, it's essential to understand how Shopware 6.7 handles caching. The platform utilizes a sophisticated cache system that includes multiple cache types such as:
- HTTP Cache
- Twig Template Cache
- Doctrine Cache
- Configuration Cache
- Asset Cache
- Product Cache
Each cache type serves a specific purpose and can be cleared independently to maintain optimal performance without affecting other components.
Method 1: Using the Cache Clear Command
The most straightforward approach to clear specific caches programmatically is through the built-in cache clearing commands. In Shopware 6.7, you can execute these commands directly from your PHP code:
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
public function clearSpecificCache(string $cacheType): void
{
$application = new Application();
$application->setAutoExit(false);
// Clear specific cache types
switch ($cacheType) {
case 'http':
$input = new ArrayInput(['command' => 'cache:clear', '--env' => 'prod', '--no-warmup' => true]);
break;
case 'doctrine':
$input = new ArrayInput(['command' => 'doctrine:cache:clear-metadata']);
break;
case 'twig':
$input = new ArrayInput(['command' => 'cache:clear', '--env' => 'prod', '--no-warmup' => true]);
break;
default:
$input = new ArrayInput(['command' => 'cache:clear', '--env' => 'prod', '--no-warmup' => true]);
}
$output = new BufferedOutput();
$application->run($input, $output);
}
Method 2: Direct Cache Service Injection
For more granular control, you can directly inject and use cache services available in Shopware 6.7's dependency injection container:
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class CacheManager
{
private TagAwareCacheInterface $cache;
public function __construct(
TagAwareCacheInterface $cache,
CacheItemPoolInterface $doctrineCache
) {
$this->cache = $cache;
$this->doctrineCache = $doctrineCache;
}
public function clearSpecificCache(string $cacheKey): void
{
// Clear specific cache key
$this->cache->invalidateTags(['shopware']);
// Clear doctrine cache for specific entities
if ($this->doctrineCache instanceof CacheItemPoolInterface) {
$this->doctrineCache->clear();
}
}
public function clearProductCache(string $productId): void
{
$this->cache->invalidateTags(['product-' . $productId]);
}
}
Method 3: Using Shopware's Built-in Cache Clearing Services
Shopware 6.7 provides dedicated services for cache management that offer more control over specific cache clearing operations:
use Shopware\Core\Framework\Cache\CacheClearer;
use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
class AdvancedCacheClearer
{
private CacheClearer $cacheClearer;
private EntityCacheKeyGenerator $keyGenerator;
public function __construct(
CacheClearer $cacheClearer,
EntityCacheKeyGenerator $keyGenerator
) {
$this->cacheClearer = $cacheClearer;
$this->keyGenerator = $keyGenerator;
}
public function clearProductCache(string $productId): void
{
// Clear product specific cache
$this->cacheClearer->clear(['product-' . $productId]);
// Clear related caches
$this->cacheClearer->clear([
'product-list',
'category-tree',
'navigation-menu'
]);
}
public function clearTemplateCache(): void
{
// Clear template cache specifically
$this->cacheClearer->clear(['twig']);
}
}
Method 4: Custom Cache Clearing Implementation
For advanced use cases, you might need to implement custom cache clearing logic. Here's how to create a comprehensive cache clearing solution:
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\AbstractAdapter;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class CustomCacheManager implements CacheManagerInterface
{
private TagAwareCacheInterface $cache;
private LoggerInterface $logger;
public function __construct(
TagAwareCacheInterface $cache,
LoggerInterface $logger
) {
$this->cache = $cache;
$this->logger = $logger;
}
public function clearSpecificCache(array $tags, bool $force = false): void
{
try {
// Validate cache tags
if (empty($tags)) {
$this->logger->warning('No cache tags provided for clearing');
return;
}
// Clear specific cache tags
$this->cache->invalidateTags($tags);
$this->logger->info(
sprintf(
'Successfully cleared %d cache tags: %s',
count($tags),
implode(', ', $tags)
)
);
} catch (\Exception $exception) {
$this->logger->error(
'Failed to clear cache: ' . $exception->getMessage()
);
}
}
public function clearCacheByType(string $type): void
{
$cacheTags = match ($type) {
'product' => ['product-*', 'product-list'],
'category' => ['category-*', 'category-tree'],
'navigation' => ['navigation-*', 'menu-*'],
'config' => ['config-*', 'system-config'],
default => ['*']
};
$this->clearSpecificCache($cacheTags);
}
public function clearAllCaches(): void
{
// Clear all caches with proper logging
$this->logger->info('Starting full cache clearing operation');
$this->cache->invalidateTags(['*']);
$this->logger->info('Full cache clearing completed successfully');
}
}
Method 5: Asynchronous Cache Clearing
For performance-critical applications, consider implementing asynchronous cache clearing:
use Symfony\Component\Messenger\MessageBusInterface;
use Shopware\Core\Framework\MessageQueue\AsyncMessage;
class AsyncCacheClearer
{
private MessageBusInterface $messageBus;
public function __construct(MessageBusInterface $messageBus)
{
$this->messageBus = $messageBus;
}
public function clearCacheAsync(array $tags): void
{
// Dispatch cache clearing as async message
$clearMessage = new CacheClearMessage($tags);
$this->messageBus->dispatch($clearMessage);
}
}
class CacheClearMessage implements AsyncMessage
{
private array $tags;
public function __construct(array $tags)
{
$this->tags = $tags;
}
public function getTags(): array
{
return $this->tags;
}
}
Best Practices for Cache Clearing
When implementing cache clearing in Shopware 6.7, follow these best practices:
Performance Considerations
// Only clear necessary caches to avoid performance impact
public function smartCacheClear(array $changedEntities): void
{
$cacheTags = [];
foreach ($changedEntities as $entity) {
switch ($entity) {
case 'product':
$cacheTags[] = 'product-list';
$cacheTags[] = 'product-search';
break;
case 'category':
$cacheTags[] = 'category-tree';
$cacheTags[] = 'navigation-menu';
break;
}
}
// Clear only required tags
if (!empty($cacheTags)) {
$this->cache->invalidateTags(array_unique($cacheTags));
}
}
Error Handling and Logging
public function robustCacheClear(array $tags): bool
{
try {
$this->cache->invalidateTags($tags);
return true;
} catch (\Exception $exception) {
$this->logger->error('Cache clearing failed: ' . $exception->getMessage());
return false;
}
}
Environment-Specific Clearing
public function clearEnvironmentCache(string $environment): void
{
if ($environment === 'prod') {
// Production cache clearing with specific tags
$this->cache->invalidateTags(['shopware', 'product', 'category']);
} else {
// Development environment can be more aggressive
$this->cache->invalidateTags(['*']);
}
}
Monitoring Cache Clearing Operations
Implement proper monitoring to track cache clearing operations:
public function clearAndMonitor(array $tags): void
{
$startTime = microtime(true);
try {
$this->cache->invalidateTags($tags);
$endTime = microtime(true);
$duration = ($endTime - $startTime) * 1000;
// Log performance metrics
$this->logger->info(
sprintf(
'Cache cleared in %.2f ms for tags: %s',
$duration,
implode(', ', $tags)
)
);
} catch (\Exception $exception) {
$this->logger->error('Cache clearing failed: ' . $exception->getMessage());
throw $exception;
}
}
Conclusion
Shopware 6.7 provides robust mechanisms for programmatically clearing specific caches, allowing developers to maintain optimal performance while implementing custom functionality. By understanding the different cache types and using appropriate clearing methods, you can ensure your applications remain responsive and efficient.
The key is to choose the right method based on your specific use case:
- Use direct commands for simple scenarios
- Implement service injection for granular control
- Consider asynchronous clearing for high-performance requirements
- Always include proper error handling and monitoring
Remember that cache clearing should be performed judiciously, targeting only the necessary cache segments to avoid unnecessary performance overhead. With these techniques, you'll be able to effectively manage your Shopware 6.7 cache system and maintain optimal application performance.