Naterade
Naterade

Reputation: 2675

PHP prevent parent class from multiple instantiation from children?

So currently my class DATABASE uses a singleton for a connection and is called in the constructor of my class SQL. I have 4 other classes that extend class SQL for access to its methods. The problem is, the children instantiate each other in some cases so I'm afraid I'm creating multiple class SQL objects because they call their parent constructor by default, aka class SQL. I read about dependency injection, but no clear how to implement it in my situation so this is what I was thinking. Have all classes extend class DATABASE and make class SQL methods static. But then I would have to call the singleton connection in class DATABASE, on its own class as so.

class DATABASE {

    function __construct() {
        self::getInstance();
        /// or DATABASE::getInstance ( im not quite positive which way )
    }

    public static function getInstance() { 
        if (self::$instance == false) { 
        self::$instance = new DATABASEMANAGER(); 
        } 

        return self::$instance; 
    } 
}

I figure this way, since all classes extend class DATABASE, and instantiate each other, I know I am not creating multiple objects. I hope this makes sense and I can elaborate more if you need me to, but does this make since as an approach to my problem?

Upvotes: 1

Views: 1096

Answers (1)

Nazariy
Nazariy

Reputation: 6088

I guess you building your class other way around, this approach is more consistent in my opinion.

class DATABASE extends DATABASEMANAGER
{
    static $instance;

    private function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
        if (empty(self::$instance))
        {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

Usage:

class Blog
{
    public function __construct()
    {
        $this->database = DATABASE::getInstance();
    }

    public function getRecord($id)
    {

        $result = $this->database->query("SELECT * FROM blog WHERE id='{$id}'");
        //or
        $result = DATABASE::getInstance()->query("SELECT * FROM blog WHERE id='{$id}'");

        //other actions...
    }
}

Upvotes: 2

Related Questions