4

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?

4

2 回答 2

7

介绍

首先,你同时打破了里氏替换原则单一职责原则

因此,您将一遍又一遍地面临类似的问题。

语言服务提供商:

您的A服务器是一个容器的目的,即简单地存储数据。然后你延长这个,最终破坏is-a关系。这是因为容器不是处理程序。has-a是要走的路。您可以通过$handler_constructor

SRP:

由于您C同时服务 3 个职责,因此肯定会破坏Single Responsibility Principle. 第一个是data container,第二个是做B的,第三个是做的C

这也称为deep inheritance,这显然是一种不好的做法,直到它满足SRPLSP

一个示例,说明如何在遵守SRPLSPDI.

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);

那么,你会在这里得到什么?重用能力,从而减少代码重复。


既然你也这样做DBcore::get('foo')了,你可能想阅读这篇文章

于 2013-08-03T18:40:39.517 回答
0

您可以更改$dataprotected并使用它,

$this->data['name'];
于 2013-08-03T16:11:08.297 回答