1

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

jsonx
  • 1,093
  • 3
  • 14
  • 21

3 Answers3

1

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

prodigitalson
  • 60,050
  • 10
  • 100
  • 114
  • Actually first I thought it as a decorator. But as far as I understand decorator should add new methods/skills to existing object. Thus I couldn't decide. – jsonx Jan 13 '10 at 21:03
  • Well the thin is IMO this shouldnt be applied to your DB class directly regardless of if its an adapter or decorator unless its just a return format (aka DB::ASSOC, DB::JSON, DB::OBJ, etc.). Otherwise the proper place for it is really directly on the class that Models the data in the array you return from `getRow` or on a decorator that wraps such a model object. – prodigitalson Jan 13 '10 at 21:13
0

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.

Kevin Goff
  • 1,331
  • 1
  • 13
  • 18
  • This is the question I don't plan using DbAdapter in another class. Can we still say it is an adapter. – jsonx Jan 13 '10 at 21:01
0

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.

Anurag
  • 140,337
  • 36
  • 221
  • 257