Sharing objects between PHP classes

2019-01-28 06:41发布

问题:

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?

回答1:

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).



回答2:

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.



回答3:

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).



回答4:

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.



回答5:

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)



标签: php oop