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->ge开发者_Go百科tRows($params)) . '}';
}
}
Thanks
Id say its more of Decorator... http://en.wikipedia.org/wiki/Decorator_pattern
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.
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.
精彩评论