Skip to content

Instantly share code, notes, and snippets.

@LogansUA
Last active January 21, 2020 04:28
Show Gist options
  • Save LogansUA/4d8760aaf71bbd526f5e86b3f70c9947 to your computer and use it in GitHub Desktop.
Save LogansUA/4d8760aaf71bbd526f5e86b3f70c9947 to your computer and use it in GitHub Desktop.
Symfony2 clear route cache by deleting app<Environment>UrlGenerator.* and app<Environment>UrlMatcher.* files
<?php
namespace AppBundle\Service;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\File\File;
/**
* Class ClearRouteCacheService
*/
class ClearRouteCacheService
{
/**
* @var Filesystem $fs Filesystem
*/
private $fs;
/**
* @var Router $router Router
*/
private $router;
/**
* @var string $cacheDir Cache dir path
*/
private $cacheDir;
/**
* Constructor
*
* @param Filesystem $fs Filesystem
* @param Router $router Router
* @param string $kernelCacheDir Cache dir path
*/
public function __construct(Filesystem $fs, Router $router, $kernelCacheDir)
{
$this->fs = $fs;
$this->router = $router;
$this->cacheDir = $kernelCacheDir;
}
/**
* Clear cache
*/
public function clearRouteCache()
{
// Delete routing cache files
$finder = new Finder();
/** @var File $file */
foreach ($finder->files()->depth('== 0')->in($this->cacheDir) as $file) {
if (preg_match('/UrlGenerator|UrlMatcher/', $file->getFilename()) === 1) {
$this->fs->remove($file->getRealPath());
}
}
$this->router->warmUp($this->cacheDir);
}
}
# AppBundle/Resources/config/services.yml
services:
app.bundle.redirect_manager:
class: AppBundle\Service\ClearRouteCacheService
arguments:
- "@filesystem"
- "@router"
- "%kernel.cache_dir%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment