我创建了两个非常基本的接口,名为ReaderInterface和WriterInterface,但是我已经从这个例子中删除了WriterInterface,因为没有必要说明我的难题。
ReaderInterface.php
interface ReaderInterface
{
public function read();
}
我有一个名为Datatable的具体类:
Datatable.php
class Datatable
{
protected $cols;
protected $rows;
protected $reader;
public function __construct()
{
$this->cols = array();
$this->rows = array();
$this->reader = null;
}
public function setReader(ReaderInterface $reader)
{
$this->reader = $reader;
}
public function load()
{
//Contents to follow below.
}
}
我实例化一个数据表实例,如下所示:
$db = new PDO("mysql:host=localhost;port=3306;dbname=test", "user", "pass"); //Let's pretend this is a good connection.
$datatable = new Datatable();
$datatable->setReader(new DatatableReader($db));
$datatable->load();
我的问题是关于实现DatatableReader,以便它可以从我传入的数据库中读取,并在我的Datatable对象中写入$this->cols
和$this->rows
。
我看到了两种方法。
1。依赖注入
class DatatableReader implements ReaderInterface
{
protected $db;
protected $datatable;
public function __construct(Datatable &$datatable, PDO &$db)
{
$this->datatable = $datatable;
$this->db = $db;
}
public function read()
{
//Execute prepared statement which returns 5 records.
//Get the columns, and place them into an array.
foreach ($columns as $col) {
$this->datatable->addColumn($col); //Add a column to the datatable.
}
}
}
然后,我的Datatable::load()
方法将实现为:
public function load()
{
if ($this->reader != null)
$this->reader->read();
}
2。从read()返回弱的返回。
class DatatableReader implements ReaderInterface
{
protected $db;
public function __construct(PDO &$db)
{
$this->db = $db;
}
public function read()
{
//Execute prepared statement which returns 5 records.
//Get the columns, and place them into an array.
return $columns;
}
}
然后我会调用我的load()
方法,如下所示:
public function load()
{
if ($this->reader != null) {
$retval = $this->reader->read();
//Do stuff with the array of information returned from the reader.
}
}
问题
答案 0 :(得分:1)
我会选择选项2.使用选项1可以产生递归:DatatableReader
包含对象Datatable
,反之亦然。
选项1的另一个坏处是你滥用read
方法写入另一个对象。
只有具体实现(DatatableReader
)知道该对象。
实现接口的所有对象都应以相同的方式作出反应。