CacheController.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console\controllers;
  8. use Yii;
  9. use yii\console\Controller;
  10. use yii\console\Exception;
  11. use yii\caching\Cache;
  12. /**
  13. * This command allows you to flush cache.
  14. *
  15. * @author Alexander Makarov <[email protected]>
  16. * @since 2.0
  17. */
  18. class CacheController extends Controller
  19. {
  20. /**
  21. * Lists the caches that can be flushed.
  22. */
  23. public function actionIndex()
  24. {
  25. $caches = [];
  26. $components = Yii::$app->getComponents();
  27. foreach ($components as $name => $component) {
  28. if ($component instanceof Cache) {
  29. $caches[$name] = get_class($component);
  30. } elseif (is_array($component) && isset($component['class']) && strpos($component['class'], 'Cache') !== false) {
  31. $caches[$name] = $component['class'];
  32. }
  33. }
  34. if (!empty($caches)) {
  35. echo "The following caches can be flushed:\n\n";
  36. foreach ($caches as $name => $class) {
  37. echo " * $name: $class\n";
  38. }
  39. } else {
  40. echo "No cache is used.\n";
  41. }
  42. }
  43. /**
  44. * Flushes cache.
  45. * @param string $component Name of the cache application component to use.
  46. *
  47. * @throws \yii\console\Exception
  48. */
  49. public function actionFlush($component = 'cache')
  50. {
  51. /** @var Cache $cache */
  52. $cache = Yii::$app->getComponent($component);
  53. if (!$cache || !$cache instanceof Cache) {
  54. throw new Exception('Application component "'.$component.'" is not defined or not a cache.');
  55. }
  56. if (!$cache->flush()) {
  57. throw new Exception('Unable to flush cache.');
  58. }
  59. echo "\nDone.\n";
  60. }
  61. }