should I pass $db variable to function or not?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
bwan37
Forum Newbie
Posts: 9
Joined: Thu May 22, 2008 11:42 am

should I pass $db variable to function or not?

Post by bwan37 »

Is it a good practices to pass a conneection variable to function instead of trying make the connect within the function?
My problem is, that I don't know if I should choice "Option 1" or "Option 2" in index.php
Can someone point me to the right direction?
Thank you very much!

Code: Select all

//Database class that handle all insert/update/delete/etc...
class Database {
 function __construct { init the connection }
 function connect('host','user','pass','database')
 function insert()
 function delet()
 function disconnect()
 etc...
}


index.php
//so, now I can gain access to database using the following function...
$db = new Database();
$db->insert(...);

//Here I am trying to build a function in index.php
//Option 1: pass $db into method
function doSomething($db) {
 $db->getUserInfo()....
}

//Option 2: create new database object within the function.
function doSomething() {
 $db = new Database();
 $db->getUserInfo()....
 unset($db);
}
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: should I pass $db variable to function or not?

Post by social_experiment »

I would go with option 2; make the connection in the constructor of class Database, anytime you then create an instance of the class that connection is made.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: should I pass $db variable to function or not?

Post by Christopher »

Is $db only ever used in doSomething()? If not then I would pass it into each function that uses it.
(#10850)
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

Re: should I pass $db variable to function or not?

Post by koen.h »

Option 2 should be avoided if you want to test your code. Option 1 makes it easy to create a dummy database and check whether your code has called the right method on it. With option 2 your code depends on the database class and you actually need to be 100% sure it works or you may think something is not quite right with your doSomething method while it is actually your database that is causing problems.

Option 2 should also be avoided if you want to dynamically be able to switch to another database.

Option 2 should also be avoided if you want to know which code depends on what classes without going through your code line by line.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: should I pass $db variable to function or not?

Post by social_experiment »

koen.h wrote: need to be 100% sure it works or you may think something is not quite right with your doSomething method while it is actually your database that is causing problems.
I've had this problem then i started throwing exceptions to determine whether the connection to the database was established before using it
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: should I pass $db variable to function or not?

Post by Christopher »

For most PHP apps, I have found that creating the DB object in the boostrap in injecting it into objects as needed works best. Most apps only use one DB connection and those that have multiple can either create the others in the bootstrap as well, or create them as needed if only in one spot. I am sure there are exceptions to this rule -- like an app that only uses DB connection in one place. And, I usually defer connecting to the database until queries are actually done. That removes that overhead for non-DB pages or static/cached pages.
(#10850)
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: should I pass $db variable to function or not?

Post by VladSun »

koen.h wrote:Option 2 should be avoided if you want to test your code. Option 1 makes it easy to create a dummy database and check whether your code has called the right method on it.
I agree and disagree ;)

What is a "right method"? Or even what is the right sequence/set of DB methods called? If the so called "DB object" is a sort of DBAL one, then how do you check that the right "DBAL pseudo-SQL" is properly written (mocking the DBAL doesn't help)? E.g.:

Code: Select all

class CurrentUser {
  function __construct($db) { ... }
  function authorize($user, $pass) {
     $exist = $this->db->
       from('user')->
       filterByUser($user)->
       filterByPassword($password)->
       findOne();

    if (!$exist) {
      throw new Exception('User/pass not found.');
    }
  }
}
IMHO, the only way is to have a DatabaseTestCase which requires a true DB connection and DB records assertions.

It has been bothering me for a long time, so I would appreciate any comments on it ...

Currently, I tend to move such "queries" into separate methods in the ORM classes. Still, in order to test these classes I need some "real world" DB tests.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: should I pass $db variable to function or not?

Post by Christopher »

VladSun wrote:IMHO, the only way is to have a DatabaseTestCase which requires a true DB connection and DB records assertions.
I'm not sure I agree with this. There are two sorts of testing to do on a DB Connection object. One is to deal with problems that occur when the database itself fails for some reason, the other is to deal with different data that can be returned -- such as no results found. I think both of these sorts of cases can be mocked and be tested.
VladSun wrote:It has been bothering me for a long time, so I would appreciate any comments on it ...

Currently, I tend to move such "queries" into separate methods in the ORM classes. Still, in order to test these classes I need some "real world" DB tests
The classic tiered approach has a Datasource layer (DBAL style object) and a Domain layer (Model objects). That separates out testing into the layers. The question is whether you can focus the tests for each layer on only what is important for that layer -- thereby getting reasonable test coverage.
(#10850)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: should I pass $db variable to function or not?

Post by josh »

Its counter intuitive but you should pass your dependencies in. Even better than passing in the database object is passing in data already selected as an array, for example. This is because your code will have less dependencies and be less coupled.
annaharris
Forum Commoner
Posts: 30
Joined: Mon Mar 25, 2013 6:52 am

Re: should I pass $db variable to function or not?

Post by annaharris »

Option 1 is more appropriate than option 2.
Post Reply