Strategy for developing namespaced and non-namespaced versions of same PHP code

前端 未结 9 2026
时光取名叫无心
时光取名叫无心 2020-12-23 13:43

I\'m maintaining library written for PHP 5.2 and I\'d like to create PHP 5.3-namespaced version of it. However, I\'d also keep non-namespaced version up to date until PHP 5.

9条回答
  •  隐瞒了意图╮
    2020-12-23 14:17

    Here's the best answer I think you're going to be able to find:

    Step 1: Create a directory called 5.3 for every directory w/ php5.3 code in it and stick all 5.3-specific code in it.

    Step 2: Take a class you want to put in a namespace and do this in 5.3/WebPage/Consolidator.inc.php:

    namespace WebPage;
    require_once 'WebPageConsolidator.inc.php';
    
    class Consolidator extends \WebpageConsolidator
    {
        public function __constructor()
        {
            echo "PHP 5.3 constructor.\n";
    
            parent::__constructor();
        }
    }
    

    Step 3: Use a strategy function to use the new PHP 5.3 code. Place in non-PHP5.3 findclass.inc.php:

    // Copyright 2010-08-10 Theodore R. Smith 
    // License: BSD License
    function findProperClass($className)
    {
        $namespaces = array('WebPage');
    
        $namespaceChar = '';
        if (PHP_VERSION_ID >= 50300)
        {
            // Search with Namespaces
            foreach ($namespaces as $namespace)
            {
                $className = "$namespace\\$className";
                if (class_exists($className))
                {
                    return $className;
                }
            }
    
            $namespaceChar = "\\";
        }
    
        // It wasn't found in the namespaces (or we're using 5.2), let's search global namespace:
        foreach ($namespaces as $namespace)
        {
            $className = "$namespaceChar$namespace$className";
            if (class_exists($className))
            {
                return $className;
            }
        }
    
        throw new RuntimeException("Could not load find a suitable class named $className.");
    }
    

    Step 4: Rewrite your code to look like this:

    = 50300)
    {
            $includePrefix = '5.3/';
    }
    
    require_once $includePrefix . 'WebPageConsolidator.inc.php';
    
    $className = findProperClass('Consolidator');
    $consolidator = new $className;
    
    // PHP 5.2 output: PHP 5.2 constructor.
    // PHP 5.3 output: PHP 5.3 constructor. PHP 5.2 constructor.
    

    That will work for you. It is a cludge performance-wise, but just a little, and will be done away with when you decide to stop supporting 5.3.

提交回复
热议问题