NYCPHP Meetup

NYPHP.org

[nycphp-talk] OO & database connections

Tim Gales tgales at tgaconnect.com
Thu Jul 15 21:59:41 EDT 2004


 putamare writes:
> 
> Here's a best practices question: my script has several objects, say 
> one to do authorization and one or more others to display content, or 
> whatever. Most, if not all, of these objects access multiple 
> databases, 
> one for authorization, one for content, etc.
> 
> Is it better to have object create its own private connection object 
> (in my case I'm goofing off with the new mysqli_ functions, but I'm 
> sure this would apply equally to PEAR::DB, or even an old school 
> connection string), or creating a single connection object 
> and passing 
> that around to the other objects as needed?
> 

One thing is that a user's authorization to do things 
is typically determined by the permissions which are granted to 
him. Once a user is authenticated MySQL knows what that 
user can and can't do.

This authentication process is pretty well 
tuned to be fast.

In general terms, I would suggest that you 
set up usernames for each role or roles that 
you want your objects to be authorized to play.
(in other words going and selecting role information 
from a separate table is a relatively time consuming 
operation when compared to how quickly MySQL can 
do effectively the same thing under the hood)

The actual process of creating a connection is pretty 
slow.

You could create a class that has a 
$db_link variable set up (during construction) with 
a procedural call something like 

$this->db_link = mysqli_connect("localhost", "main_user", "main_password",
"usual_db");

Then if a function (inside the class -- aka method) had to switch
databases 
to do something, you could try something along the lines of

mysqli_change_user($this->db_link, "special_user", "special_password",
"special_db");

and could keep the connection and just take advantage of the (fast) 
authentication operation. 

I would be fairly wary though of a design that required  
classes to go to different databases to get things done -- 
I don't see how the class structure could be too coherent. 
One of the tenets of OO design it to keep all data 
that is functionally related in one place -- not in 
disparate databases.

T. Gales & Associates
'Helping People Connect with Technology'

http://www.tgaconnect.com





More information about the talk mailing list