0

简要说明

我目前正在构建一个 Web 应用程序,其中包括许多父类(基类)的扩展。很像下面的结构:

Class A // Base Class
    -> Class B // Extension
    -> Class C // Extension
    // etc

扩展包含特定于站点该区域的功能,例如,我站点的“文档”部分将有自己的类(基类的扩展),并且该类将包含与打开,编辑,删除文档等...

但是,我的应用程序的主导航菜单有一个交互式下拉菜单,其中显示了由其中几个“扩展”类中的方法收集的信息。

我的问题

目前,为了访问为我的导航菜单收集数据所需的所有方法,我必须创建几个扩展类的实例,如下所示:

require_once(class.a.php);
require_once(class.b.php);
require_once(class.c.php);

// Create an instance of Class B to get the data for the first dropdown
$b = new B();

// Gather the data for the first dropdown
$dropdown[0] = $b->get_document_data();

// Create an instance of Class C to get the data for the second dropdown
$c = new C();

// Gather the data for the second dropdown
$dropdown[1] = $c->get_settings_statistics();

虽然创建对象的新实例并不完全是“世界末日”,但我的父类构造函数非常大,因此,我不想每页有多个实例......

结果,我只能看到另一种选择,我只需将必要的方法放入父类中......鉴于我的类的工作方式,这不是很实用!

因此,我想知道的是您是否可以创建一个对象的实例,然后为它单独加载单独的扩展?

或者,如果您能想到更好的方法来实现这一点,请随时提供您的观点...

4

2 回答 2

0

您可以只支持组合而不是继承:

 class A {
     public function __construct(){ /* heavy lifting here */ }

     public function coolSharedMethod(){}
 }

 class B {
     protected $a;
     public function __construct(A $myA){
          $this->a = $myA;
     }

     // proxy methods through
     public function coolSharedMethod(){
          return $this->a->coolSharedMethod();
     }
 }

如果 A 的初始化相同,但它包含需要根据具体情况更改的状态,您可能需要查看原型设计模式

 $a = new A();
 $b = new B(clone $a);
 $c = new C(clone $a);
于 2013-05-28T19:02:54.137 回答
-2

我可能会为每个类使用通用静态方法并以 IoC 模式传递一个对象:

<?php

class A
{
    public static function init_nav_menu(&$menu_object)
    {
        // do nothing in base class
    }
}

class B extends A
{
    public static function init_nav_menu(&$menu_object)
    {
        // manipulate menu_object here, giving it info needed for dropdown
    }
}

// (load class files)

$menu = new stdClass;
B::init_nav_menu($menu);
//C::init_nav_menu($menu);
//...
于 2013-05-28T18:36:10.087 回答