jsonx
jsonx

Reputation: 1090

PHP Design Pattern

I have a class that performs database operations and returns results (array, true, false). And I have an another class that creates JSON string by using this class in its constructor. Can we say this class is an Adapter? Or simply wrapper or ...

Class Db
{
    public function getRows($params)
    {
        //...
    }
}


Class DbAdapter
{
    private $_dbh;
    public function __construct($dbh)
    {
        $this->_dbh = $dbh;
    }

    public function getJson()
    {
        return '{"key": "foo", "key2": ' . json_encode($this->_dbh->getRows($params)) . '}';
    }
}

Thanks

Upvotes: 1

Views: 687

Answers (3)

Anurag
Anurag

Reputation: 141859

I don't think you can pick one pattern and say that's the one being used here. Here's my little list of patterns I see in your example. Feel free to comment.

Delegation because the DBAdapter class delegates the task of getting the actual rows to the DB class.

Decorator because the DBAdapter class decorates the DB class with additional functionality - that of spitting the output in JSON.

Adapter/Wrapper if you think that it allows other client to access your database rows that only understood JSON or XML or some other format.

But if we had to pick one, I'd say Adapter. It takes the data in the form of PHP data structures and converts it into a JSON representation.

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

Id say its more of Decorator... http://en.wikipedia.org/wiki/Decorator_pattern

Upvotes: 1

Kevin Goff
Kevin Goff

Reputation: 1331

From: http://www.fluffycat.com/PHP-Design-Patterns/Adapter/

Adapters are helpful if you want to use a class that doesn't have quite the exact methods you need, and you can't change the orignal class. The adapter can take the methods you can access in the original class, and adapt them into the methods you need.

I would say your code qualifies as an adapter if you plan to add methods to supplement another class.

Upvotes: 0

Related Questions