Hi all,
Just a question to see how other people tackle this same problem.
Say you've got a model "Film" that should only show films on the site when
certain conditions are met. But... you don't want to specify the conditions in
every occurrence. However, you need to be able to override these conditions in
certain areas - eg. the admin section of the site where you need to be able to
edit unpublished films.
eg.
using:
$this->Film->findAll();
instead of:
$this->Film->findAll('Film.publishable = 1 AND Film.release_date <= NOW()');
And to override these conditions, you would use:
$this->Film->findUnpublished = true;
$this->Film->findAll();
My solution is below. It should be pretty flexible - you can use arrays or
strings for your conditions, or a mixture of both. I am thinking of moving the
methods (currently in AppModel) into a behaviour for better encapsulation, but
I'm not yet sure what to call it :)
Can anybody give feedback on my method, and if anyone suggests doing anything
else?
Cheers,
Adam
.
<?php
class Film extends AppModel {
var $name = 'Film';
// should we show all films, or only ones publicly available
var $findUnpublished = false;
function beforeFind(&$data){
if (!$this->findUnpublished) {
$conditions = 'Film.publishable = 1 AND Film.release_date <= NOW()';
$data['conditions'] = $this->mergeConditions($data['conditions'],
$conditions);
}
}
}
?>
<?php
class AppModel extends Model {
function flattenConditions($conditions) {
if (!is_null($conditions)) {
$db = &ConnectionManager::getDataSource($this->useDbConfig);
return $db->conditions($conditions, true, false);
}
return '';
}
function mergeConditions() {
$args = func_get_args();
$conditions = array();
foreach ($args as $arg) {
$sql = $this->flattenConditions($arg);
if ($sql) {
$conditions[] = $sql;
}
}
if ($conditions) {
return '('.implode(') AND (', $conditions).')';
}
return '';
}
}
?>
And here is how I override it in my controller.
<?php
class FilmsController extends AppController {
var $name = 'Films';
function beforeFilter() {
parent::beforeFilter();
if (!empty($this->params[CAKE_ADMIN])) {
$this->Film->findUnpublished = true;
}
}
function admin_index() {
$this->Film->recursive = 0;
$this->set('films', $this->paginate());
}
}
?>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Cake
PHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---