PHP解决方法来扩展同名的类?

时间:2011-08-11 16:38:59

标签: php oop

我知道扩展一个具有相同名称的类是不可能的,但我很好奇是否有人知道加载类然后重命名它的方法,所以我可以稍后用原始名称扩展它。希望喜欢以下内容:

<?php 
//function to load and rename Class1 to Class2: does something like this exist?
load_and_rename_class('Class1', 'Class2');

//now i can extend the renamed class and use the original name:
class Class1 extends Class2{
}
?>

编辑: 好吧,我知道在基本的OOP环境中这将是一个糟糕的做法,那里有大型的类文件库。但是我正在使用CakePHP MVC框架,因为框架遵循一个完善的命名约定(模型名称,视图名称,控制器名称,URL路由(http:/),因此能够以这种方式扩展插件类是非常有意义的。 /site.com/users)等)。

截至目前,要扩展CakePHP插件(例如:Users插件),您必须通过添加前缀(如AppUsers)扩展所有具有不同名称的模型,视图和控制器类,然后再进行一些编码以重命名变量名称,然后您必须编码重命名的URL路由等,以最终回到'用户'名称约定。

由于MVC框架代码组织良好,如果能够实现上述类似的代码,那么在代码中很容易理解。

2 个答案:

答案 0 :(得分:0)

我正在努力找出为什么这是必要的。我只能想到以下例子:

在您无法控制的上下文中,初始化了一个对象:

// A class you can't change
class ImmutableClass {
    private function __construct() {
        $this->myObject = new AnotherImmutableClass();
    }
}

$immutable = new ImmutableClass();

// And now you want to call a custom, currently non existing method on myObject
// Because for some reason you need the context that this instance provides
$immutable->myObject->yourCustomMethod();

所以现在你想在不编辑Immutable类的情况下向AnotherImmutableClass添加方法。

这绝对不可能。

您可以从该上下文中做的就是将该对象包装在装饰器中,或运行辅助函数,传递该对象。

// Helper function
doSomethingToMyObject($immutable->myObject);
// Or decorator method
$myDecoratedObject = new objectDecorator($immutable->myObject);
$myDecoratedObject->doSomethingToMyObject();

很抱歉,如果我得到了错误的结束。

有关装饰器的更多信息,请参阅以下问题: how to implement a decorator in PHP?

答案 1 :(得分:0)

我碰巧理解你为什么要这样做,并想出办法来实现最终目标。对于其他人来说,这是作者可能正在处理的一个例子......

通过CakePHP应用程序,您可能会引用帮助程序类(例如&gt; $ this-&gt; Form-&gt; input();)

然后在某些时候你可能想要向input()函数添加一些内容,但仍然使用Form类名,因为它已经完成了你的应用程序。同时,虽然您不想重写整个Form类,而只是更新它的一小部分。所以考虑到这个要求,实现它的方法是......

你必须从Cake核心中复制现有的类,但你不要对它进行任何更改,然后当你升级蛋糕时,你只需要复制到这个新目录。 (例如,将lib / Cake / View / Helper / FormHelper.php复制到app / View / Helper / CakeFormHelper.php)

然后,您可以添加一个名为app / View / Helper / FormHelper.php的新文件,并让FormHelper扩展CakeFormHelper,即

App::uses('CakeFormHelper', 'View/Helper');

FormHelper extends CakeFormHelper {
    // over write the individual pieces of the class here
}
相关问题