Created
February 11, 2013 16:15
-
-
Save mozmorris/4755451 to your computer and use it in GitHub Desktop.
CakePHP "Expires" behavior. Works with 1.2. I don't think any changes are required to get it working with 2.0. Ensure you've added `expiry_date` (DATE) column to your model table.
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 | |
class ExpiresBehavior extends ModelBehavior { | |
protected $_defaults = array( | |
'field' => 'expiry_date' | |
); | |
/** | |
* Setup this behavior with the specified configuration settings. | |
* | |
* @param object $model Model using this behavior | |
* @param array $config Configuration settings for $model | |
* @access public | |
*/ | |
function setup(&$model, $config = array()) { | |
// merge existing settings or defaults with the model config | |
$this->settings[$model->alias] = array_merge( | |
isset($this->settings[$model->alias]) ? $this->settings[$model->alias] : $this->_defaults, | |
$config | |
); | |
// throw exception if the model's db field doesn't exists in the db table | |
if (!array_key_exists($this->settings[$model->alias]['field'], $model->_schema)) { | |
throw new Exception( | |
sprintf( | |
"%s field does not exist in the %s table", | |
$this->settings[$model->alias]['field'], | |
$model->useTable | |
), | |
1); | |
} | |
} | |
/** | |
* Before find callback | |
* | |
* @param object $model Model using this behavior | |
* @param array $queryData Data used to execute this query, i.e. conditions, order, etc. | |
* @return boolean True if the operation should continue, false if it should abort | |
* @access public | |
*/ | |
function beforeFind(&$model, $query) { | |
// if a condition is already set, then do nothing | |
if (array_key_exists($this->settings[$model->alias]['field'], $query)) { | |
return $query; | |
} | |
// merge existing query with the expiry condition | |
return Set::merge($query, array( | |
'conditions' => array( | |
// return records that have their expiry date in the future | |
$model->alias . '.' . $this->settings[$model->alias]['field'].' >=' => date('Y-m-d') | |
) | |
)); | |
} | |
} | |
?> |
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 | |
class Gist extends AppModel { | |
var $name = 'Gist'; | |
// include Expires behavior | |
var $actsAs = array( | |
'Expires' | |
); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment