我创建了两个非常基本的接口,名为 ReaderInterface 和 WriterInterface,但我从这个示例中删除了 WriterInterface,因为没有必要说明我的难题。
读者界面.php
interface ReaderInterface
{
public function read();
}
我有一个名为 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 以便它可以从我传入的数据库中读取,$this->cols
并$this->rows
在我的 Datatable 对象中写入和写入。
我马上就看到了两种方法。
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.
}
}
问题
- 在这两个选项中,哪个是最好的设计?
- 我忽略了第三种选择吗?