Tower
Tower

Reputation: 102905

Building a third-party PHP library that requires a database access

I am building a 3rd-party library that requires a database access. To be more specific, it's an access control library. Currently the biggest problem I am facing is that how do I make it compatible with most frameworks and CMS's?

I could issue queries using a database instance that the developer specifies. This has three problems:

Or I could just have methods that return the SQL, but is that any better?

Upvotes: 3

Views: 233

Answers (2)

Gordon
Gordon

Reputation: 317089

The Adapter Design Pattern springs to mind

An “off the shelf” component offers compelling functionality that you would like to reuse, but its “view of the world” is not compatible with the philosophy and architecture of the system currently being developed.

For your concrete problem this means you create a class for your framework that exposes an API with all the method required by your other classes. This is the only interface you will interact it. Then you create adapters for each database you want to support. So your adapter will become the meditator between your framework and the DAL.

Example:

interface DB_Interface
{
    public function somethingYourFrameworkUses();
}

class YourDB implements DB_Interface
{
    public function setAdapter(DB_Interface $adapter)
    {
        $this->adapter = $adapter;
    }
    public function somethingYourFrameworkUses()
    {
        $this->adapter->somethingYourFrameworkUses();
    }
}

The above is your main class. You will only interact with this class from your remaining framework's code. The functionality required to interact with a specific database is contained within a concrete adapter then. You instantiate and inject an adapter at runtime.

class PDO_Adapter implements DBInterface
{
    public function somethingYourFrameworkUses()
    {
        // code to make this function work with PDO
    }
}

class MySQLi_Adapter implements DBInterface
{
    public function somethingYourFrameworkUses()
    {
        // code to make this function work with MySQLiAdapter
    }
}

Add additional adapters as you see fit.

Upvotes: 2

Billy ONeal
Billy ONeal

Reputation: 106579

You could build on top of an existing database abstraction layer like Zend_Db, which will let you write the code once and it'll work everywhere.

Upvotes: 0

Related Questions