【发布时间】:2012-03-21 00:33:00
【问题描述】:
在我目前正在开发的一个模块中,我尝试将需求建模为具有正确关系的类图。
要求:
- 该模块将连接到一组 ftp 服务器并下载一些文件。
- 该模块将解析每个文件以生成一组发票。
所以我创建了 4 个类 File、Ftp 和 Parser。现在我想我应该让 File 类能够download()和parse() 本身。
class File{
private $supplier;
private $status;
private $fileName;
private $fileId;
function __construct($supplier){
$this->supplier=$supplier;
}
function downloadFile(){
$ftp= new Ftp($this->supplier);
$this->fileName=$ftp->download();
}
function parseFile(){
$parser= new Parser($this); // The parse needs the fileName in addition to the supplier info to parse the file correctly.
$parser->parse();
}
function saveFileInfoToDB(){
//Save file Info to db.
}
}
所以每当我需要下载文件时,我都会执行以下操作:
class ServiceInvoker{
function downloadFilesFromFtpServers(){
foreach($suppliers as $supplier){
/*$supplier here is an object containing all data needed to download a file
from that certain supplier filled from the database
(i.e. ftpUsername, ftpPassword, ftpHost, SupplierName, supplierFileType).*/
try{
$file= new File($supplier);
$file->downloadFile()
$file->saveFileInfoToDB();
}catch(Exception $e){
//log error
}
}
}
}
您可以清楚地看到,要下载一个文件,我必须在不同的对象中进行多次下载调用。
我认为问题主要是因为我认为 File 类应该能够自行下载,因此我在 File 类本身中实例化了一个 Ftp 对象。
当我尝试解析文件时也会发生同样的情况,因为我需要将 $this 传递给解析器以获取文件的信息。
我认为 Ftp 类应该直接在 ServiceInvoker 中传递 Supplier 的对象,如果进程成功下载该文件,则使其返回 File 对象。
现在我应该如何正确识别类 Ftp Parser 和 File 之间的关系? File 是否应该包含解析器对象,或者解析器本身是否应该包含 File 对象并直接从服务调用程序调用?我可以清楚地将 Parser 和 File 类之间的关系识别为关联。 Ftp 和文件类之间相同,但谁应该包含谁?
【问题讨论】:
标签: php uml associations class-design aggregation