0

This article is similar to my needs, but I'm more curious about a specific solution to it, and if it's a good or bad idea to do it. Sharing objects between PHP classes

Say, like in the link above, I have an object I want to pass to multiple classes, say a $db object.

Instead of using dependency injection and passing it to each method's constructor, is it ever a good idea to let all the classes extend a Base class, that stores the $db object as a property?

For example:

abstract class Base {
    protected static $_db;
    public function setDatabase( Database $db ) {
        $this->_db = $db;
    }
    public function getDatabase() {
        return $this->_db;
    } 
} 

class SomeClass extends Base {
    public function doStuff() {
       $result = $this->getDatabase()->query(.....);
    }
}

Which would mean all classes that extend Base need not worry about grabbing/checking/setting the $db themselves, as they'd already have that object as a property as soon as the class is defined.

I know dependency injection is the usual way to go, but is this ever a viable solution?

Thanks!

2 Answers 2

0

You still have to set the db on each instance of the class - setting it on one instance doesnt set it on all instances... unless of course its a static property.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I forgot to write static above! I am already using static on the real code. So you agree that it is an okay solution (as long as static is used)?
well i ont think i would recommend it... what if you have a couple instances that need to use a different connection? At the least you should be able to pass in a connection to each method that interacts with the db if you use a static... That said i have done it this way before, so i cant really fault you for it. I guess it depends on the complexity of you app :-)
Hmm. One solution could be to let the OtherClass override get/setDatabase to use it's own $db variable if needed. Thanks for your help!
0

That is perfectly fine. I have used it before and never ran into any issues.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.