我的目的是在 php 中创建两种类型的图形:饼图、线性图和相互表示数据。
每个图表都应该有自己的设置表示,例如:标签、文本。
在饼图中,需要将指标数量显示为数字或百分比。
我从定义接口(interface)和抽象类开始:
interface IGraph {
function percent();
function percentGroup($type);
}
abstract class Graph implements IGraph {
abstract function source();
abstract function percent();
abstract function percentGroup($type);
}
class GraphPie extends Graph {
function source() {}
function percent() {}
function percentGroup($type) {}
}
我意识到应该是一个通用的抽象类Graph
和自定义类如GraphPie
、GraphLinear
。
我的问题是为此任务创建整个类结构。例如,我需要创建另一个类作为 GraphModelClass
来编写从 db 检索数据的方法吗?
换句话说,当我按模式检索数据时,我需要构建功能,并且可以在任何图形中表示它。
我尝试在我的案例中采用模式。我已经审查了以下模式:工厂、门面,但它不适合我。
我关注这个短instruction关于使用模式:
最佳答案
一般来说,如果您的代码将依赖于您或其他人编写的其他代码的不同实现,您只需要一个接口(interface)
。如果要为多个数据模型实现单个 View ,则可以使用 interface
。然后, View 可以访问具有接口(interface)形式的契约的模型。
但在您的情况下,您想以另一种方式进行操作:对具有百分比和组名称的聚合数据使用单一模型,对同一类型的数据使用多个 View (折线图、饼图)。
你不需要为此使用对象继承。创建一个模型来检索和存储数据库中的数据。然后在绘制折线图或饼图的每个 View 类中使用相同的模型。
如果您的类名为 GraphLine
和 GraphPie
,您可以像这样使用单继承:
class GraphBase { /* generic draw functions, like labels */ }
class GraphLine extends GraphBase { /* Line graph specific drawing */ }
class GraphPie extends GraphBase { /* Pie chart specific drawing */ }
对于数据,您可以像这样创建一个类 DataModel
class DataModel {
protected $iYear;
public function setYear(int $iYear) : self {}
public function getGraphData() : array { /* SQL SELECT .. GROUP BY .. */ }
}
然后在 GraphBase
中:
class GraphBase {
protected $oDataModel;
public function setDataModel(DataModel $oDataModel) : self {
$this->oDataModel = $oDataModel;
return $this;
}
abstract function draw(); // GraphPie and GraphLine should implement this
}
用法:
$Model = new DataModel;
$Model->setYear(2017);
$LineGraph = new GraphLine;
$LineGraph
->setDataModel($Model)
->draw();
关于php - 如何在 PHP 中创建抽象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49835533/