coderex
coderex

Reputation: 27855

Which design pattern use when different libraries to create a Spreadsheet?

In my controller class I just want to use only one spreadsheet class to handle all the functions related to spreadsheet creation, save, load, write etc.

Currently I'm using one open source library phpspreadsheet to create a spreadsheet, if later I want to change that to another library of spreadsheet creation, I don't want to change much on the controller class, instead, I can create another class for this library, like Spreadsheetlib2. So which design pattern is better to use here? "Bridge" or Adapter?

// Bridge Pattern what I'm trying now.

interface SpreadsheetInterface {

    public function create();

    public function write();

}


class Spreadsheet extends AbstractSpreadsheet {

    public function create() {

    }
}



class PhpSpreadsheet implements SpreadsheetInterface {

    public function create() {

    }
}


abstract class AbstractSpreadsheet {

    protected $spreadsheet;

    protected function __construct(SpreadsheetInterface $spreadsheet) {
        $this->spreadsheet = $spreadsheet;
    }
}

Upvotes: 0

Views: 117

Answers (2)

Flosculus
Flosculus

Reputation: 6946

Heres a little trick that Doctrine uses to define a Connection interface, while extending PDO at the same time.

interface Connection
{
    public function prepare ($statement, array $driver_options = array());
}

class PdoConnection extends \PDO implements Connection
{

}

So, they wanted to define an interface that they could implement based on the requirements of whatever DB they were connecting to. But they wanted to keep the API pretty similar to PDO, however PDO doesn't implement an interface, so they had to piggy back one onto it by extending PDO while implementing Connection, therefore PDO unwittingly implements the methods of Connection.

You can do the same really. Choose whichever spreadsheet library you like best and create an interface from its methods, create a new class extending it then implement your interface.

Now when you want to switch implementation, your favourite library ought to have provided you with a decent amount of method signatures to implement another version.

Upvotes: 0

tereško
tereško

Reputation: 58444

I would really pay that much attention to "what pattern to use". Patterns are not magical recipes, to write your code by. They are just "shorthand descriptions", that you use to describe stuff you already wrote, to some other developer.

The way I would do it would be creating a wrapper (I think that counts as "adapter"), which implements some specific interface, that you Controller depends upon. And in this wrapper I would pass the PhpSpreadsheet instance as a dependency (or create a new instance of it directly in that wrapper).

When your controller calls a method on the wrapper, it forwards the call to the underlying "spreadsheet class.

Upvotes: 1

Related Questions