Welcome Guest, Not a member yet? Register   Sign In
What is the best way to write "delete" functions in a model?
#1

[eluser]aquary[/eluser]
I have been using my own custom MY_model, which contains basics DB functions like create(), update(), delete() and other stuffs, for a while. All of them accept $cfg to specify the condition and setting for the query, which is parsed and set by the prepare() function inside the MY_model. To call the function, I'd write a code like this in the controller:
Code:
// this would delete all data with parent=3 and status=1 in the default table of the model
$cfg->where=array('parent'=>3, 'status'=>1);
$this->accounts->delete($cfg);
// or use this to delete data in another table
$this->accounts->delete($cfg, 'TABLE_NAME_HERE');

Lately, I'm quite curious about the code. The $cfg is easy for me to do the same stuff without writing similar functions with minor different (eg. delete_account($id), delete_unactive_accounts(), delete_xxx_accounts()). But in other way, I'm quite bored of setting $cfg every time to delete or select data. Many times I'd forget to reset the $cfg and send a wrong setting, or forget to set the condition, which resulted in all rows in a table updated with the same values.

For everyone else, how you handle this kind of functions? Are you using "One function to rules them all", or "Write a right function for a right task" ?
#2

[eluser]Jelmer[/eluser]
I'm using a similar setup (though with RapidDataMapper instead of Active Record). My base model contains general functions which could work on all tables, but when I implement the base model for different tables I configure them by overwriting the parent function but almost always still use it in the end (the new function does some checking and configuring, the actual deleting is done by the parent).

Also I limit the usage of my general update and delete functions to work solely by ID. That prevents many mistakes, like the one you mentioned. If there's a reason I might need a function to work on multiple rows I write specialized functions for that instead of using the general ones, mainly because I don't need such functions very often and they're very prone to mistakes.
#3

[eluser]aquary[/eluser]
So you'd call something like this, not the normal update(), delete().
Code:
$this->accounts->delete_something_specific($id);
$this->accounts->update_more($id);

Thanks, that clear me up quite a lot Smile
#4

[eluser]Jelmer[/eluser]
I do call them delete() and update(), but a little bit more logical might be delete_by_id($id) and update_by_id($id).

Other functions I name for their function, for example: remove_expired_autologins() which will remove all autologin keys in a login library that are too old.




Theme © iAndrew 2016 - Forum software by © MyBB