是否可以动态扩展一个类?

Spo*_*pot 26 php oop class extend

我有一个类,我需要根据标准扩展不同的类(最多数百个).PHP中有没有办法通过动态类名扩展类?

我假设它需要一个方法来指定实例化的扩展.

想法?

Jac*_*ane 27

虽然它仍然不可能而且不完全是你的答案我需要相同的东西,并且不想使用eval,monkey-patching等.所以我在条件中使用默认类来扩展它.

当然这意味着如果你有100个课程要扩展,你需要用另一个扩展操作添加100个条件,但对我来说这看起来是正确的方式.

<?php
if(class_exists('SolutionClass')) {
    class DynamicParent extends SolutionClass {}
} else {
    class DynamicParent extends DefaultSolutionClass {}
}

class ProblemChild extends DynamicParent {}
?>
Run Code Online (Sandbox Code Playgroud)

  • 我有Zend Framework(特别是Magento)的问题,第三方模块出现并扩展了我已经扩展的类.使用这种方法,我可以改变我的类来动态扩展第三方类,而不是我们都追求的核心类. (2认同)
  • 优秀的解决方案,而且如此简单!(“啰嗦”?!伙计们,你们见过替代方案吗?:))我无法停止喜欢它,并把我的头撞到桌子上,我没有想出它...... (2认同)

Dan*_*ack 8

可以使用magic __call函数的强大功能在PHP中创建动态继承.它需要一些基础设施代码才能工作,但并不是太令人生畏.

放弃

在使用这种技术之前,你真的应该至少考虑两次,因为这实际上是一件坏事.

我使用这种技术的唯一原因是因为我不想在创建网站模板时创建接口定义或设置依赖注入.我希望能够在模板中定义几个函数"块",然后继承自动使用正确的"块".

履行

所需的步骤是:

  • 子类现在扩展了一个'DynamicExtender'类.此类拦截子类所做的任何调用,以及子类中不存在的方法,并将它们重定向到父实例.

  • 每个'ParentClass'都扩展为'ProxyParentClass'.对于父类中的每个可访问方法,"ProxyParentClass"中存在等效方法.'ProxyParentClass'中的每个方法都会检查ChildClass中是否存在该方法,并调用该函数的子版本(如果存在),否则它将调用ParentClass中的版本

  • 构造DynamicExtender类时,传入所需的父类,DynamicExtender创建该类的新实例,并将自身设置为ParentClass的子类.

所以,现在当我们创建子对象时,我们可以指定所需的父类,DynamicExtender将为我们创建它,它看起来好像子类是从我们在运行时请求的类扩展而不是它很难-coded.

这可能更容易理解为几个图像:

固定继承是固定的

在此输入图像描述

使用代理进行动态继承

在此输入图像描述

演示实施

这个解决方案的代码可以在Github上找到,并且在这里可以使用稍微全面的解释,但上面图像的代码是:

//An interface that defines the method that must be implemented by any renderer.
interface Render {
    public function render();
}


/**
 * Class DynamicExtender
 */
class DynamicExtender implements Render {

    var $parentInstance = null;

    /**
     * Construct a class with it's parent class chosen dynamically.
     *
     * @param $parentClassName The parent class to extend.
     */
    public function __construct($parentClassName) {
        $parentClassName = "Proxied".$parentClassName;

        //Check that the requested parent class implements the interface 'Render'
        //to prevent surprises later.
        if (is_subclass_of($parentClassName, 'Render') == false) {
            throw new Exception("Requested parent class $parentClassName does not implement Render, so cannot extend it.");
        }

        $this->parentInstance = new $parentClassName($this);
    }

    /**
     * Magic __call method is triggered whenever the child class tries to call a method that doesn't
     * exist in the child class. This is the case whenever the child class tries to call a method of
     * the parent class. We then redirect the method call to the parentInstance.
     *
     * @param $name
     * @param array $arguments
     * @return mixed
     * @throws PHPTemplateException
     */
    public function __call($name, array $arguments) {
        if ($this->parentInstance == null) {
            throw new Exception("parentInstance is null in Proxied class in renderInternal.");
        }

        return call_user_func_array([$this->parentInstance, $name], $arguments);
    }

    /**
     * Render method needs to be defined to satisfy the 'implements Render' but it
     * also just delegates the function to the parentInstance.
     * @throws Exception
     */
    function render() {
        $this->parentInstance->render();
    }
}



/**
 * Class PageLayout
 *
 * Implements render with a full HTML layout.
 */
class PageLayout implements Render {

    //renders the whole page.
    public function render() {
        $this->renderHeader();
        $this->renderMainContent();
        $this->renderFooter();
    }

    //Start HTML page
    function renderHeader() {
        echo "<html><head></head><body>";
        echo "<h2>Welcome to a test server!</h2>";

        echo "<span id='mainContent'>";
    }

    //Renders the main page content. This method should be overridden for each page
    function renderMainContent(){
        echo "Main content goes here.";
    }

    //End the HTML page, including Javascript
    function renderFooter(){
        echo "</span>";
        echo "<div style='margin-top: 20px'>Dynamic Extension Danack@basereality.com</div>";
        echo "</body>";
        echo "<script type='text/javascript' src='jquery-1.9.1.js' ></script>";
        echo "<script type='text/javascript' src='content.js' ></script>";
        echo "</html>";
    }

    //Just to prove we're extending dynamically.
    function getLayoutType() {
        return get_class($this);
    }
}

/**
 * Class ProxiedPageLayout
 *
 * Implements render for rendering some content surrounded by the opening and closing HTML
 * tags, along with the Javascript required for a page.
 */
class ProxiedPageLayout extends PageLayout {

    /**
     * The child instance which has extended this class.
     */
    var $childInstance = null;

    /**
     * Construct a ProxiedPageLayout. The child class must be passed in so that any methods
     * implemented by the child class can override the same method in this class.
     * @param $childInstance
     */
    function __construct($childInstance){
        $this->childInstance = $childInstance;
    }

    /**
     * Check if method exists in child class or just call the version in PageLayout
     */
    function renderHeader() {
        if (method_exists ($this->childInstance, 'renderHeader') == true) {
            return $this->childInstance->renderHeader();
        }
        parent::renderHeader();
    }

    /**
     * Check if method exists in child class or just call the version in PageLayout
     */
    function renderMainContent(){
        if (method_exists ($this->childInstance, 'renderMainContent') == true) {
            return $this->childInstance->renderMainContent();
        }
        parent::renderMainContent();
    }

    /**
     * Check if method exists in child class or just call the version in PageLayout
     */
    function renderFooter(){
        if (method_exists ($this->childInstance, 'renderFooter') == true) {
            return $this->childInstance->renderFooter();
        }
        parent::renderFooter();
    }
}


/**
 * Class AjaxLayout
 *
 * Implements render for just rendering a panel to replace the existing content.
 */
class AjaxLayout implements Render {

    //Render the Ajax request.
    public function render() {
        $this->renderMainContent();
    }

    //Renders the main page content. This method should be overridden for each page
    function renderMainContent(){
        echo "Main content goes here.";
    }

    //Just to prove we're extending dynamically.
    function getLayoutType() {
        return get_class($this);
    }
}

/**
 * Class ProxiedAjaxLayout
 *
 * Proxied version of AjaxLayout. All public functions must be overridden with a version that tests
 * whether the method exists in the child class.
 */
class ProxiedAjaxLayout extends AjaxLayout {

    /**
     * The child instance which has extended this class.
     */
    var $childInstance = null;

    /**
     * Construct a ProxiedAjaxLayout. The child class must be passed in so that any methods
     * implemented by the child class can override the same method in this class.
     * @param $childInstance
     */
    function __construct($childInstance){
        $this->childInstance = $childInstance;
    }

    /**
     * Check if method exists in child class or just call the version in AjaxLayout
     */
    function renderMainContent() {
        if (method_exists ($this->childInstance, 'renderMainContent') == true) {
            return $this->childInstance->renderMainContent();
        }
        parent::renderMainContent();
    }
}



/**
 * Class ImageDisplay
 *
 * Renders some images on a page or Ajax request.
 */
class ImageDisplay extends DynamicExtender {

    private $images = array(
        "6E6F0115.jpg",
        "6E6F0294.jpg",
        "6E6F0327.jpg",
        "6E6F0416.jpg",
        "6E6F0926.jpg",
        "6E6F1061.jpg",
        "6E6F1151.jpg",
        "IMG_4353_4_5_6_7_8.jpg",
        "IMG_4509.jpg",
        "IMG_4785.jpg",
        "IMG_4888.jpg",
        "MK3L5774.jpg",
        "MK3L5858.jpg",
        "MK3L5899.jpg",
        "MK3L5913.jpg",
        "MK3L7764.jpg",
        "MK3L8562.jpg",
    );

    //Renders the images on a page, along with a refresh button
    function renderMainContent() {
        $totalImages = count($this->images);
        $imagesToShow = 4;
        $startImage = rand(0, $totalImages - $imagesToShow);

        //Code inspection will not be available for 'getLayoutType' as it
        //doesn't exist statically in the class hierarchy
        echo "Parent class is of type: ".$this->getLayoutType()."<br/>";

        for($x=0 ; $x<$imagesToShow ; $x++) {
            echo "<img src='images/".$this->images[$startImage + $x]."'/>";
        }

        echo "<br/>&nbsp;<br/>";
        echo "<span onclick='loadImagesDynamic();' style='border: 2px solid #000000; padding: 4px:'>Click to refresh images</span>";
    }
}


$parentClassName = 'PageLayout';

if (isset($_REQUEST['panel']) && $_REQUEST['panel']) {
    //YAY! Dynamically set the parent class.
    $parentClassName = 'AjaxLayout';
}

$page = new ImageDisplay($parentClassName);

$page->render();
Run Code Online (Sandbox Code Playgroud)


Ste*_*nte 7

我不认为动态扩展课程是可能的(但如果我错了,我很想知道它是如何完成的).你有没有想过使用复合模式(http://en.wikipedia.org/wiki/Composite_pattern,http://devzone.zend.com/article/7)?您可以动态合成另一个类(甚至多个类 - 这通常用作多重继承的工作),以将父类的方法/属性"注入"子类.


Jac*_*eaf 7

你不能只使用 eval 吗?

<?php
function dynamic_class_name() {
    if(time() % 60)
        return "Class_A";
    if(time() % 60 == 0)
        return "Class_B";
}
eval(
    "class MyRealClass extends " . dynamic_class_name() . " {" . 
    # some code string here, possibly read from a file
    . "}"
);
?>
Run Code Online (Sandbox Code Playgroud)

  • 我通常对于在任何类型的生产环境中使用 eval() 都非常犹豫。 (6认同)
  • @Jared eval 函数在这种情况下并不邪恶。其次,要时刻牢记“权力越大,责任越大”。 (2认同)
  • 我使用 class_alias 函数设置了一个动态类名,如 `class_alias('TCPDF', 'TCPDF2');` 。我已经解决了我的同样类型的问题。第一个参数定义原始类名,第二个参数定义新类名。然后我们可以在 if 和 else 条件下使用这个函数。如果有人想要这个方法使用扩展动态类来解决继承问题,我可以给一个演示。 (2认同)

Bha*_*mar 7

我已经解决了我的同样类型的问题。第一个参数定义了class_alias函数的原始类名,第二个参数定义了新的类名。然后我们可以在 if 和 else 条件下使用这个函数。

if(1==1){
  class_alias('A', 'C');
}
else{
  class_alias('B', 'C');
}

class Apple extends C{
      ...
}
Run Code Online (Sandbox Code Playgroud)

Apple 类扩展到虚拟类“C”,根据 if 和 else 条件,可以将其定义为类“A”或“B”。

有关更多信息,您可以查看此链接https://www.php.net/manual/en/function.class-alias.php


Pav*_*iev 5

是。我喜欢用eval回答,但是很多人害怕代码中的任何eval,所以这里是一个没有eval的答案:

<?php //MyClass.php 
namespace my\namespace;
function get_dynamic_parent() {
    return 'any\other\namespace\ExtendedClass';// return what you need
}
class_alias(get_dynamic_parent(), 'my\namespace\DynamicParent');

class MyClass extends DynamicParent {}
Run Code Online (Sandbox Code Playgroud)