所以我有一个名为foo的类,并且有两种在mongo或mysql中存储数据的方法。
目前我有类似的东西
namespace vendor;
use bar;
use bar'mysql;
class foo extends bar'mongo {
}
现在有更好的方法吗?我知道有我只是不知道它是哪种模式(如果有的话)。
可以应用的原则称为:
偏爱组合而不是继承
这意味着不是从这些对象继承,而是提供这些对象的类实例,然后对其执行操作。
例如:
class Mysql
{
function getItems($what)
{
//return items from mysql
}
}
class MongoDB
{
function getItems($what)
{
//return items from MongoDB
}
}
class Foo
{
protected $db;
public function __construct($db)
{
$this->$db = $db;
}
public function getFooItems()
{
$this->db->getItems('foo')
}
}
$db = new Mysql();
$foo = new Foo($db)
$foo->getFooItems(); //Will operate on the mysql db
$db1 = new MongoDB();
$foo1 = new Foo($db1);
$foo1->getFooItems(); //Will operate on the MongoDB
我希望这有帮助