层次结构中的OO编程 - 如何检索对象

时间:2012-11-05 12:39:11

标签: php oop

我想知道哪种方法是检索包含两个表数据的对象的最佳方法。 在我的情况下,我想检索一个投资组合项目,该项目组合项目包含在portfolioItem表格中,另一个表格包含图像。

现在我正在努力争取哪个是在对象中检索这些项目的最佳方法。 在第一种方式中,我在Data类中一次检索所有内容并返回完整对象,而第二种方式是从两个不同的数据类构建对象(一个用于一般投资组合信息,一个用于图像)。

现在我只是想知道,有没有比其他方式更好的方式或两种方式都可以接受? 可以立即获取所有数据,还是应该像第二种方式一样分解它?

我有两个表:portfolioItem和portfolioItemImage 我有一个像

这样的课程
PortfolioItem{
    public $portfolioItemId;
    public $name;
    public $images //array
}

1:

$dataPortfolioItem = new DataPortfolioItem();
$theItem = $dataPortfolioItem->getPortfolioItem(5);
DataPortfolioItem{
    public function getPortfolioItem($theId){
        //create a new portfolio item
        //get the portfolio data from portfolioItem table and fill in the id and name
        //get the image data from image table and set the images array from the object
        //return the object with the data and images included
    }
}

2:

$dataPortfolioItem = new DataPortfolioItem();
$theItem = $dataPortfolioItem->getPortfolioItem(5);
$dataPortfolioItemImages = new DataPortfolioItemImages();
$theItem->images = $dataPortfolioItemImages->getPortfolioItemImages(5)

DataPortfolioItem{
    public function getPortfolioItem($theId){
        //create a new portfolio item
        //get the portfolio data from portfolioItem table and fill in the id and name
        //return the portfolio item     
    }
}

DataPortfolioItemImage{
    public function getPortfolioItemImages($theId){
        //get the images from the database table and return them in an array
    }
}

1 个答案:

答案 0 :(得分:1)

“在我的情况下,我想要检索投资组合项目......”。如果是这种情况,则您的数据访问层(DAL)应返回Portfolio对象,而不是在两个单独的对象中返回它。

关于设计的一些一般性事项。 您的应用程序逻辑应该基于您的模型,不应该知道数据存储的详细信息。如果是这种情况,那么您的DAL应该只提供Model对象。

除了: “方法从两个不同的数据层构建对象,一个用于portfolioItem数据,另一个用于图像。”通过图层,您可能意味着表格。层是不同的。

相关问题