4

I am using a php library and it has the following function:

public function call(\Phalcon\Mvc\Micro $application);

but in old version of this library this function was like:

public function call($application);

so when I implement this function in my code I have to change the signature of implemented function according to the version of this library I am using. How can I support both versions without the need to build two versions of my code for each one?

Anas Salman
  • 372
  • 3
  • 16
  • You want implement a class which extends a library's class with the call method? – Vasily Aug 06 '15 at 10:23
  • yes I did that, but the implemented function signature varies according to the base library, if I used the old version of the library there is no restriction on parameter type but when I use the new one I have to specify parameter type, if i didn't do this my code will break at runtime – Anas Salman Aug 06 '15 at 10:37
  • I've tried to override a method in extended class on my local mashine (with php 5.5 on board) and it works - I've overrided func(array $a) with func($a). I think you can't do it in previos versions of php. Also I've found this question - http://stackoverflow.com/questions/13423494/why-is-overriding-method-parameters-a-violation-of-strict-standards-in-php which claims that it's violation of Liskov substitution principle. – Vasily Aug 06 '15 at 11:21
  • Why do you need to support both versions? – Romain Lanz Nov 09 '15 at 10:20

1 Answers1

2

I ended up doing the following, 1- first I have created a factory to get the right implementation based on phalcon version:

class X
{
    public static function getMiddleware(){
        $oX = new X();

        if ((int)\Phalcon\Version::getId()/1000000 >= 2) {
            return new XV2($oX);
        } else {
            return new XV1($oX);
        }
    }

    public function call($application)
    {
       // do your business here 
    }
}

2- then I have implemented this class twice based on the right interface, but the actual call will be in the caller class:

class XV1 implements MiddlewareInterface
{

    private $_oX;

    public function __construct($oX)
    {
        if (!isset($oX) || $oX == null){
            throw new Exception("X couldn't be null or empty");
        }
        $this->_oX = $oX;
    }

    public function call($application)
    {
        return $this->_oX->call($application);
    }

}


class XV2 implements MiddlewareInterface
{

    private $_oX;

    public function __construct($oX)
    {
        if (!isset($oX) || $oX == null){
            throw new Exception("X couldn't be null or empty");
        }
        $this->_oX = $oX;
    }

    public function call(\Phalcon\Mvc\Micro $application)
    {
        return $this->_oX->call($application);
    }

}

if anyone has a better solution please share it with us

Anas Salman
  • 372
  • 3
  • 16