Passing Database class into constructor?
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();
}
}
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.
Several things:
- 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.
- if you want auto complete - put a type hint in the function declaration
public function toto(DataBaseClass $MyDB,array $params){...}
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.
精彩评论