2

What's a better practice? To pass database or open database? I'm unable to do an auto-complete (NetBeans PHP IDE) when I pass a database into the constructor.

class Item {
    private $name;
    private $database;

    public function __construct($database, $id) {
        $information = $database->fetchSingleRow($id);

        $this->database = $database;
        $this->name = $information['name'];
    }
}

Should I do this

class Item {
    private $name;
    private $database;

    public function __construct($id) {
        $this->database = new Database();
        $this->database->open();
        $this->database->select('test'); // selects test table

        $information = $this->$database->fetchSingleRow($id);
        $this->name = $information['name'];
    }

    public function __destruct() {
        unset($this->item);
        $this->database->close();
    }
}

3 Answers 3

1

I'd personally pass it as an argument in the constructor. If you have many instances of Item, a new connection is created every time, which would strain your database.

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

Comments

1

Several things:

  1. A DB object is usually better to get by factory/singelton/registery and not move it around. Unless you have the ability to hold thousands of open connections in one request.
  2. if you want auto complete - put a type hint in the function declaration

 

public function toto(DataBaseClass $MyDB,array $params){...}

Comments

0

It has already been covered that creating a new instance of the database everytime you instianiate an Item will become a strain on the DB, but I would also like to point that it really wouldn't be a good design decision.

The main problem here is that you aren't following the "principle" of speration of design. If you were to have Item create a new Database object, you'd run into issues down the road of if you wanted to change ANYTHING about how the database was created/open/etc. You'd have to change everywhere in your codebase that created a new Database instance. Thus not being ready for change.

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.