-1

So if I have an interface iConnection

interface iConnection
{
}

Which is implemented by:

class OutlookConnection implements iConnection
{
}

And

class GoogleConnection implements iConnection
{
}

And another interface iComparison

interface iComparison
{
}

Which is implemented by:

class OutlookComparison implements iComparison
{
  private $connection;
  public function __construct($user, iConnection $iConnection) {
   $this->connection = $iConnection;
  }
}

And

class GoogleComparison implements iComparison
{
  private $connection;
  public function __construct($user, iConnection $iConnection) {
   $this->connection = $iConnection;
  }
}

In the main program I want to be able to switch between GoogleComparison and OutlookComparison based on the iConnection type without using an if or switch statement:

public function __construct(iConnection $connection)
{
    $this->connect = $connection;
    if($this->connection instanceof GoogleConnection){
      $this->comparison = new GoogleComparison();
    }
    elseif($this->connection instanceof OutlookConnection){
      $this->comparison = new OutlookComparison();
    }
}

Is this possible to achieve within this constructor without switch or if statements?

Sinan Samet
  • 6,432
  • 12
  • 50
  • 93

1 Answers1

2

This is an architectural issue. I suggest passing responsibility for providing comparison to the connection. One of the possible solutions could look like this below.

First - interface gets getter stub:

interface iConnection
{
    public function getComparison();
}

Then - all the different connections implement it as you want, for example:

class OutlookConnection implements iConnection
{
    public function getComparison()
    {
        return new OutlookComparison();
    }
}

And finally, your construction similar to:

public function __construct(iConnection $connection)
{
    $this->connect = $connection;
    $this->comparison = $connection->getComparison();
}

From now on, you can either operate on comparison property or simply $this->connect->getComparison()->fooBarBaz(). All depends on your needs.

Michał Haracewiat
  • 488
  • 1
  • 3
  • 9