Suppose I have a two classes called User
and Product
.
Both of these need to be saved in a database.
A third class called PersistencyHandler
handles all the database interactions (in order to obey both Single Responsability Principle and Dependency Inversion).
Here is what this class looks like:
<?php
/**
* Class PersistencyHandler
* Handles database using PDO API
*/
class PersistencyHandler{
/**
* PDO connection used to save objects into.
* @var $conn PDO
*/
private $conn;
/**
* PDODatabaseSaver constructor.
* @param $conn PDO
*/
public function __construct($conn){
$this->pdo = $conn;
}
/**
* Saves the given object in the database
* @param $object mixed
*/
public function save($object){
// as PHP does not support classic method overloading for different
// types of objects, this is the cleanest solution I've been able to find.
// And it's still pretty dirty...
if($object instanceof Product) {
$this->saveProduct($object);
} else if($object instanceof User) {
$this->saveUser($object);
} else {
throw new UnsupportedOperationException("Cannot save object, unsupported type."); // custom class
}
}
private function saveProduct(Product $object){
// save Product into database
}
private function saveUser(User $object){
// save User into database
}
}
?>
I come from Java experience and I am sure that using instanceof
is a very poor practice (at least in Java). For instance, in Java, I used to solve problems like this using overloaded methods.
I have checked php.net and other websites (including this one) but I haven't found a good answer to my question:
What is the better way to achieve the same behaviour of the above code in a correct way?
Notice that I have a single method with a single argument and the called method is decided by the type of the argument.