tags:

views:

83

answers:

2

Hello.

  • Can I avoid instantiate a Db object inside of Names object to access it anyways?
  • Would __autoload work for that?
  • Is there another smart solution?

I have following classes (They are conceptual so they won't work if executed):

Db {
    function connect($config) {
     // connect to data base
    }
    function query($query) {
     // Process a query
    }
}
Names {
    function show_names($query) {
     $Db = new Db(); // Is it possible to autoload this object?
     $Db->query(query);
     // Print data
    }
}
+2  A: 

A solution that is often used for database connection related classes is to work with the Singleton Design Pattern (example of implementation in PHP).

It allows to have a class that will encapsulate the connection to the DB, and will ensure there is only one connection opened for the lifetime of the PHP script -- never more.

This will allow you to use some syntax like this :

$db = Db::getInstance();
$db->query('...');

Or :

Db::getInstance()->query('...');


About autoload : it will work, as long as : there is a way for it to map the class' name to a file.

Pascal MARTIN
+2  A: 

Classes can be autoloaded, but objects must be instantiated. It seems that your problem is trying to make these two classes more loosely coupled. Probably the simplest solution to this problem is using the Singleton design pattern. However, it is not the best solution, as you may decide to have more than 1 database connection, and it also becomes problematic in unit testing. I suggest taking a look at the concept of Dependency Injection, which is more complicated, yet much more flexible.

Ignas R
Was really the way for me to go. Opened another thread that showed the code I made: http://stackoverflow.com/questions/1418605/dependency-injection-in-php
Cudos