tags:

views:

400

answers:

5

What is the best way to share objects between other classes?

For example; a "database" object with functions that are required by the "article" and "user" objects.

I don't want to use globals (that includes singletons) or create a new instance of the object in each class, such as

function __construct() {
    $this->database = new database;
    $this->cache = new cache;
}

Would passing the objects in, eg.

class test{
    function __construct( $obj ) {
        $this->obj = $obj;
    }
}
$database = new database;
$test = new test( $database );

Be the way to go?

+4  A: 

Yes. Passing the objects to the constructor - or to a setter - is the best way to go. This pattern is known as dependency injection. It has the added benefit that it makes your code easier to test (using stubs or mocks).

Emil H
A: 

The way to go would be singletons if they have a single instance. If not, the only way is to pass them during initialization (say: in the constructor).

soulmerge
+1  A: 

Yes, that's pretty much the way you want to do. If a class has external requirements, don't create them inside the class, but require them as arguments in the constructor.

Henrik Paul
A: 

That would be a step in the right direction, but it does seem to me that you do actually want a singleton there, even if not actually constrained in code.

Kris
A: 

You could also use objects that have been loaded in session or in cache (APC,memcached) before. Personnaly i think singleton is the best way to go there (especially for database class)

mdcarter