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.
<?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') | |
) | |
)); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment