I'll continue my monologue here :)
If I understand correctly, Cake uses only one instance of each model
class using the class registery -- allowing to chain models
($this->Post->Author->Post->Author .... ) without creating an infinite
number of objects.
Does this mean, however, that I cannot trust my 'id' field of a given
model to remain the same ? For instance, say that I have a forum, where
each post can have any number of replies, and the replies can go at any
depth. If I hide a post, I want to hide all the replies with it. So in
my Post model I would have something like this :
function hide($id = null) {
if ($id) {
$this->id = $id;
}
if ($this->id) {
$this->saveField('hidden', 1);
$replies = $this->findAll('Post.parent_id' => $this->id);
foreach ($replies as $reply) {
$this->set($reply);
$this->hide();
}
}
}
And in my Author controller I would have something like :
function hideUserPosts($id) {
$posts = $this->Posts->findAll('Post.author_id' => $id);
foreach ($posts as $post) {
$this->Post->set($post); // This sets the 'id' of $this->Post
$this->Post->hide();
// But here $this->Post->id has now been changed ; which means I
cannot
// safely manipulate this Model anymore.
}
}
In order to prevent such problems from occuring, every model/behaviour
function should restore the 'id' field before returning ? So the basic
way to write a function would be :
function doSomething($id = null) {
if ($id) {
$this->id = id;
}
if ($this->id) {
$current_id = $this->id;
// Do something here which might change the 'id' field.
// calling anything on a linked model might have that effect.
$this->id = $current_id;
}
}
Does this make sense ? Maybe it would be usefull to have generic
wrapper to do all this work --
function doSomething($id = null) {
if ($this->prepareId($id)) {
// Do something
$this->restoreId();
}
}
With 'prepareId' and 'restoreId' being in AppModel. Though even better
might be to use __call ? You'd define all your behaviour/model
functions like this :
function model_doSomething() {
// Do something. When this gets called, $this->id is valid.
}
And in AppModel (this is php4 version) :
function __call($method, $args, &$return) {
if (method_exists($this, 'model_'.$method)) {
// If there are any arguments, then the first one must be the id.
if (count($args)) {
$aid = array_shift($args);
if ($aid) {
$this->id = $aid;
}
}
if ($this->id) {
$curr_id = $this->id;
$return =& call_user_func_array(array($this, 'model_'.$method),
$args);
$this->id = $curr_id;
}
return true;
}
return false;
}
What do people think ? (If anything ;) )
Anselm
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---