veeveeoor
veeveeoor

Reputation: 205

One class and many implementations

In my application I have a class Database, which contains some methods and static methods. I don't expect these methods has changed everytime, but their implementation can be changed (eg. by changing the way of data storage from SQL database to file based solution). Thus, in my application I would always refer to the Database class and be able to choose the implementation of this class.

// Code to select implementation for class Database

$db = new Database();
$data = $db->load();
$db->store($data);

$db = Database::defaultDatabase();
$db->store($data);

I could create a few Database classes with different implementations in separate files, and depending on the needs, include file with the required implementation. But I'd rather be able to choose implementation from code. I have not idea how to do it properly and in accordance with good development practice. Maybe some design pattern? The first thing that comes to my mind is the strategy or factory method, but I do not see the use for these patterns in this case.

Upvotes: 1

Views: 48

Answers (1)

veeveeoor
veeveeoor

Reputation: 205

For this moment I think, that the best solution is PHP function class_alias (link to manual). It works the way I wanted. I can create classes like TextFileDatabase, MySqlDatabase etc. which implements DatabaseInterface (or simly have the same methods without implementing any interface, but solution with DatabaseInterface is safer for me, becouse I don't have to remember which methods I should implement). And at start of the script I can select default implementation via class_alias.

class_alias('TextFileDatabase', 'Database');

$db = new Database();
$data = $db->load();
$db->store($data);

$db = Database::defaultDatabase();
$db->store($data);

Upvotes: 1

Related Questions