How to reduce PHP code?

I need to write the same piece of code again and again, and I would like to know if there is a better way or shortcut

I use 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 get the data from the grandparent class.

There is no problem, except that I need to get data very often and that the php code becomes extremely huge (the real class name is very long and getter-Functionname is very long)

What I am writing:

 databaseCore::getDataByIndex('name') 

In C, I would use a macro preprocessor:

#define DATA(x) databaseCore::getDataByIndex((x))

Is there an easy way to reduce the amount of code I have to write?

+4
source share
2 answers

intro

First of all, you violate the principle of replacing Liskov and the principle of single responsibility at the same time,

Thus, you will encounter similar problems again and again.

LSP:

Your server A is for a container that simply stores data. Then you expand it and end the is-a break. This is because the container is not a handler. has-a is the way to go. You can insert a container into this $handler , via constructor

SRP:

Since your C performs 3 responsibilities at the same time, it definitely violates the Single Responsibility Principle . The first is the data container , the second is what B does, and the third is what C does.

This is also known as deep inheritance , which is obviously bad practice until it satisfies SRP and LSP .

An example of how you can reduce code duplication by adhering to 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 get here? Reusability, which reduces code duplication.


Since you are also doing DBcore::get('foo') , you can read this article

+7
source

You can change $data to protected and use it like,

 $this->data['name']; 
0
source

Source: https://habr.com/ru/post/1495117/


All Articles