SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist hessodreamy's Avatar
    Join Date
    Apr 2005
    Location
    uk
    Posts
    525
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    Passing database handle to function vs global

    It seems like common practice to set up a database connection handle at the start of a script, and call it as a global within functions:
    Code:
    class Something
    {
    	public function doAQuery(){
    		global $database;
    		$database->query();
    	}
    
    }
    $database = setupDatabase();
    $st = new Something();
    $st->doAQuery();
    Sometimes I see people explicitly passing it as a parameter in the construction or another function call:
    Code:
    class Something
    {
    	private $database;
    	
    	public function __construct(Database $database){
    		$this->database=$database;
    	}
    	
    	public function doAQuery()
    	{
    		$this->database->query();
    	}
    
    }
    
    $database = setupDatabase();
    $st = new Something($database);
    $st->doAQuery();
    (There's singletons as well, but I'm not thinking about that right now)

    Any advantage of one over the other?

  2. #2
    SitePoint Zealot
    Join Date
    Jan 2011
    Location
    Portland
    Posts
    148
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The first one is more the old school way of doing it before we had good OOP in php. But more than that global vars are ugly, bad practice in most cases, And could lead to potential insecure code.

    The second method is considered best practice, It is using dependency injection, is simply written, much more secure & controllable. Also allows the application to scale in a much cleaner and more effective.


    But both have a time and place. Database code fits better with the second option.
    coming soon sitejuju.com my new development portfolio


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •