Re: Contributing / DB_Object
| From: | MARTY Fabien | Date: | Mon, 29 Apr 2002 22:08:34 +0000 |
| Subject: | Re: Contributing / DB_Object | ||
| References: | 1 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-5903@lists.php.net to get a copy of this message | ||
(Mika)
> On Mon, 29 Apr 2002 fabien.marty@free.fr wrote:
> > to generate your get and set methods, what about using :
> > function genericGet($field)
> > {
> > return $this->{$field};
> > }
> >
> > function genericSet($field, $value)
> > {
> > $this->{$field} = $value;
> > }
>
> Set works but get wont. What if in the extended class
> you need to pass a parameter, say a format string to
> something like get('date', ). Now you have to rewrite
> the whole genericGet() and now just getDate().
Of course. In this case, there is no solution I think.
> > I you don't like this solution (there are some reasons),
> > the only way (i think) is to make a little PHP script which
> > generate the php code you want. Then, you make a copy/paste
> > to add these trivial methods to the rest of your class.
>
> Well how do you copypaste runtime? ;)
There are a few possibilities but you could always find examples where they
don't work. So...
> > For the save() method, I use a global variable
> > $db_connection (the DB connection) and my save() method
> > is for example :
>
> IMO dbh in a global variable is bad. What if you have several
> connections to different databases? It's better to pass the dbh
> as a parameter to the constructor or factory method.
Ok, you are right. If you have several connections to differents databases...
But it was only an example. You can use :
// to save changes
function save()
{
DB_Object::update($this->db_connection, "foo", "id=$this->id", $this,
"id");
}
// to insert (new record) into database
function insert()
{
DB_Object::insert($this->db_connection, "foo", $this);
}
> Why have different methods for updating or inserting?
> Much simpler is just to have one save() method. If the
> object has an id then you know it allready exist in
> the database, if not then the object was created from
> data outside of databaase (say, submitted from a form
> or something) and then you have to an insert.
I have made two different methods for more flexibility. Your solution
is correct but what about if you want to store a copy to an
existing record ? Moreover, with the update method you can, for example,
update only a specified field with :
DB_Object::update($db_connection, "foo", "id=$this->id", $this,
"specifiedField", "only");
(...)
So it's a litlle more complex but i think you have more possibilities with
two differents methods.
Fabien
(fabien.marty@free.fr)