lundi 12 novembre 2018

PHP Overload class by other with the same name and namespace

I have a directory tree where in different sub-directories I have a lot of classes with the same name. There is a strong intention to not edit these classes.

I'm looking for a way to load one class and after using it and destroying its instance load another with exactly the same name. Then use it, destroy its instance and repeat that process.

I thought some possible solutions:

  1. Loading class with the same name that replaces previously loaded class (Overloads it)
  2. Unloading a class before I load class with the same name but from different path
  3. Creating a new class (dynamically created class body) under different name or by adding to it namespace. Creation process firstly reads source class body, its methods, properties and "copies" that to new class. Similar to clone on instances but done on class body level.

For the 3rd I thought this could be useful: Componere to create class in combination with Reflection to read source class body.

Do you have any other ideas or perhaps some solutions? Did you use componere and can say it suits the job? maybe there are other options?

Perhaps there is a OOP design pattern that covers this issue but I'm not familiar with it.

Example code:

<?php

#------------------------------------
//path Foo/Bar.php

/* class is without a namespace or have the same
as Baz/Bar.php */
class Bar
{
    public function getName() : string
    {
        return 'Foo/Bar';
    }
}

#------------------------------------
//path Baz/Bar.php

/* class is without a namespace or have the same
as Foo/Bar.php */
class Bar
{
    public function getName() : string
    {
        return 'Baz/Bar';
    }
}

#------------------------------------
//path ./Execute.php

$paths = [
    'Foo/Bar.php',
    'Baz/Bar.php'
];

$results = [];
foreach ($paths as $path) {

    //how to create instance of class Bar in Foo/Bar.php and then in Baz/Bar.php
    //without PHP Fatal error:  Cannot declare class...
    $classDynamic = ...

    $results[] = $classDynamic->getName();
    unset($classDynamic);
}

var_export($results)

/**
 * prints
 * array('Foo/Bar', 'Baz/Bar')
 */





Aucun commentaire:

Enregistrer un commentaire