This is question about class relationships not class functionality.
Currently my DBConnection
and DBQuery
classes are two separate objects
class DBConnection {
public $dbh;
__construct() {
$this->dbh = ... //Establish Connection to db
}
}
class DBQuery {
private $dbh;
__construct(PDO $dbh) {
$this->dbh= $dbh;
}
public runSQLQuery($query) {
$result = $this->dbh->execute($query);
$return $result;
}
}
$dbh = new DBConnection();
$DBQuery = new DBQuery($dbh);
$DBQuery->executeSQLQuery("SELECT * FROM mytable");
So i injecting DBConnection
to DBQuery
.
1st Question - can i have them merged as one object instead as $dbh
is unlikely to be used in any other class than DBQuery
.
Is this bad practice to group them, why?
class DBQuery {
private $dbh;
__construct() {
$this->dbh = ... //Establish Connection to db
}
public runSQLQuery($query) {
$result = $this->dbh->execute($query);
$return $result;
}
}
$DBQuery = new DBQuery();
$DBQuery->executeSQLQuery("SELECT * FROM mytable");
2nd Question - If merging is No-No then, how about extending, it keeps DBConnection
class separate so it can be used by another class if needed, class DBQuery
simply extends class DBConnection
.
They seem to be logically related so is this bad practice also, why?
class DBConnection {
public $dbh;
__construct() {
$this->dbh = ... //Establish Connection to db
}
}
class DBQuery extends DBConnection {
__construct() {
parent::__construct()
}
public runSQLQuery($query) {
$result = $this->dbh->execute($query);
$return $result;
}
}
$DBQuery = new DBQuery();
$DBQuery->executeSQLQuery("SELECT * FROM mytable");
Bottom line is i am trying to find a solution in which i dont have to instantiate extra objects (it uses too many lines of code) as well as write unneeded lines of code inside classes just to pass one to another for no obvious reason.
P.S. I am familiar with SOLID OOD and Separation of Concerns however i still see no forecast for keeping this two classes separate.
objects
, they more likeactions
that are pretty related to me. Plus they only used together all the time never separate so why i keep them in two instances. why i cannot simply save myself few lines of code and merge them. Why i got to think OO all the time vs common sense?Apple
andAnimal
areactions
what'sanimal.Eat(apple)
?Apple
is an particular object,Animal
is group of particular objects (animals).Database connection
is action of establishing electric signal between computers, not object.network packets
traveling over internet would be objects howeverconnection to database
is an action,query to database
is also an action someone making.Dog peeing
is object or action? In my logicdatabase
class isobject
whileconnection
andquery
are itsmethods
.