I have a class for each database table I have, for example events
table's rows are stored in Event
classes. For each class I write, there are several methods that are exactly the same just with different variables or column names. For example:
Player class update()
public function update() {
$conn = new PDO( db_host, db_user, db_pw );
$sql = "UPDATE players SET name=:name, picture=:picture, position=:position, num=:num, team=:team, description=:description WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":name", $this->name, PDO::PARAM_STR );
$st->bindValue( ":picture", $this->picture, PDO::PARAM_STR );
$st->bindValue( ":position", $this->position, PDO::PARAM_STR );
$st->bindValue( ":num", $this->num, PDO::PARAM_INT );
$st->bindValue( ":team", $this->team, PDO::PARAM_INT );
$st->bindValue( ":description", $this->description, PDO::PARAM_STR);
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
Team class update()
public function update() {
$conn = new PDO( db_host, db_user, db_pw );
$sql = "UPDATE teams SET name=:name, sname=:sname, logo=:logo, sport=:sport WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":name", $this->name, PDO::PARAM_STR );
$st->bindValue( ":sname", $this->sname, PDO::PARAM_STR );
$st->bindValue( ":logo", $this->logo, PDO::PARAM_STR );
$st->bindValue( ":sport", $this->sport, PDO::PARAM_STR );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
As you can see the point of the methods are the same it's just different variables being bound to the statement (this is the case with more methods). Is there an easy way to do it so that each class has the same basic update()
, insert()
, delete()
... methods but with its respective variables? I have thought of inheriting basic behaviour from a super class but from OO point of view doesn't make much sense (and im not convinced there is any way of saying "for each public variable declared in this class") but I'm not sure if there is a way to do this using compositions (or at all, really).
See Question&Answers more detail:
os