Created
April 9, 2013 22:04
-
-
Save borgand/5349827 to your computer and use it in GitHub Desktop.
Add this to your protected/components/Controller.php class to allow mixed cache keys in Yii: $this->beginCache($product)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Controller is the customized base controller class. | |
* All controller classes for this application should extend from this base class. | |
*/ | |
class Controller extends CController | |
{ | |
// Rest of the Controller class | |
/** | |
* Calculates a string ID for any kind of input. | |
* | |
* Used primarily for {@link beginCache()} | |
* @var mixed $id_data Any kind of input data | |
* @return string Hashed string of input data | |
*/ | |
function getHashedID($id_data){ | |
// Scalar types go as-is | |
if(is_scalar($id_data)){ | |
// Scalar types first | |
return (string)$id_data; | |
} | |
// Arrays are mapped recursively and joined with "/" | |
elseif (is_array($id_data)) { | |
return join("/", array_map(array($this,'getHashedID'), $id_data)); | |
} | |
// CModels are mapped to sha1 of their attributes | |
elseif (is_object($id_data) && in_array('CModel',class_parents(get_class($id_data)))) { | |
return get_class($id_data) . "-" . sha1(json_encode($id_data->attributes)); | |
} | |
// json_encode won't handle non-iterateable objects | |
// use print_r for those | |
elseif (is_object($id_data)) { | |
return get_class($id_data) . "-" . sha1(print_r($id_data, true)); | |
} | |
// Everything else is sha1 of their print_r output | |
else { | |
return sha1(print_r($id_data, true)); | |
} | |
} | |
/** | |
* Converts mixed first argument into valid string ID for {@link CBaseController::beginCache}, then calls super. | |
* | |
* @var mixed $id_data Any data that {@link getHashedID} can turn into a hash string | |
* @var array $properties Properties passed along to {@link CBaseController::beginCache} | |
* @return boolean (passed through) whether we need to generate content for caching. False if cached version is available. | |
*/ | |
public function beginCache($id_data, array $properties = array()) { | |
$id = $this->getHashedID($id_data); | |
return parent::beginCache($id, $properties); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment