I have to write the same piece of code again and again, and I'd like to know if there's a better way, or a shortcut
I'm using php, and I have 3 classes:
class A{
private $data = array( .... );
protected function get($index){
return $data[$index];
}
}
class B extends A{
}
class C extends B{
public function doSth(){
echo A::get('index');
}
}
What I want to do is to get data from the grandparent-class.
No problem, in except that I need to get data very often, and that the php-code gets extremly huge (the real classname is very long, and the getter-Functionname is very long)
That's what I'm writing:
databaseCore::getDataByIndex('name')
In C I would use a preprocessor-makro like this:
#define DATA(x) databaseCore::getDataByIndex((x))
Is there an easy way to reduce the amount of code I have to write?
First of all, you're breaking the Liskov Substitution Principle and the Single-Responsibility Principle at the same time,
Thus, you'll will be facing similar problems over and over again.
Your A
server a purpose of a container, that simple stores a data. Then you extend this one, and end up breaking is-a
relationship. This is because a container is not a hanlder. has-a
is the way to go. You can inject a container to that $handler
, via constructor
Since your C
serve 3 responsibilities at the same time, it definitely breaks the Single Responsibility Principle
. The first one is data container
, the second is something that does B
, and the third is something that does C
.
This is also known as deep inheritance
, which obviously is a bad practice, until it satisfies the SRP
and LSP
.
An example, of how you can reduce code duplication, while adhering the SRP
, LSP
and DI
.
class Container
{
protected $container = array();
public function setName($name)
{
$this->container['name'] = $name;
}
public function getName()
{
return $this->container['name'];
}
public function setAge($age)
{
$this->container['age'] = $age;
}
public function getAge()
{
return $this->container['age'];
}
}
class Handler
{
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function fetchSomething(Container $container)
{
$query = "SELECT * FROM `table` WHERE `name` =:name AND `age` =:age";
$stmt = $this->pdo->prepare($query);
$stmt->execute(array(
':name' => $container->getName(),
':age' => $container->getAge()
));
return $stmt->fetch();
}
}
$container = new Container();
$container->setName($_POST['name']);
$container->setAge($_POST['age']);
$handler = new Handler($pdo);
$stuff = $handler->fetchSomething($container);
print_r($stuff);
So, what would you gain here? The reuse-ability, thus reducing code duplication.
Since you also do DBcore::get('foo')
, you might want to read this article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With