CacheController.php 1.58 KB
Newer Older
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console\controllers;

Qiang Xue committed
10
use Yii;
11 12 13 14 15 16 17 18 19 20 21 22
use yii\console\Controller;
use yii\console\Exception;
use yii\caching\Cache;

/**
 * This command allows you to flush cache.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class CacheController extends Controller
{
Qiang Xue committed
23 24 25
	/**
	 * Lists the caches that can be flushed.
	 */
26 27
	public function actionIndex()
	{
Alexander Makarov committed
28
		$caches = [];
Qiang Xue committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
		$components = Yii::$app->getComponents();
		foreach ($components as $name => $component) {
			if ($component instanceof Cache) {
				$caches[$name] = get_class($component);
			} elseif (is_array($component) && isset($component['class']) && strpos($component['class'], 'Cache') !== false) {
				$caches[$name] = $component['class'];
			}
		}
		if (!empty($caches)) {
			echo "The following caches can be flushed:\n\n";
			foreach ($caches as $name => $class) {
				echo " * $name: $class\n";
			}
		} else {
			echo "No cache is used.\n";
		}
45 46 47 48 49 50 51 52 53 54
	}

	/**
	 * Flushes cache.
	 * @param string $component Name of the cache application component to use.
	 *
	 * @throws \yii\console\Exception
	 */
	public function actionFlush($component = 'cache')
	{
slavcodev committed
55
		/** @var Cache $cache */
Qiang Xue committed
56
		$cache = Yii::$app->getComponent($component);
resurtm committed
57
		if (!$cache || !$cache instanceof Cache) {
58 59 60
			throw new Exception('Application component "'.$component.'" is not defined or not a cache.');
		}

resurtm committed
61
		if (!$cache->flush()) {
62 63 64 65 66 67
			throw new Exception('Unable to flush cache.');
		}

		echo "\nDone.\n";
	}
}