我可以告诉你在这种情况下我会怎么做。每当我需要获取一堆数据并从中构建多个对象时,我会将整个混乱转储到另一个模型(可能是服务层,我不知道)并从控制器中整理出对象。我只是使用控制器来获取数据并将其发送到其他地方(视图或模型)。
例如,我想从我的音乐收藏中保存一些数据,这些数据当前位于 csv 文件中。我的控制器解析 csv 文件并将每一行数据放入一个数组中,我将其转发给一个类方法,该方法将数据分类为对象并将其保存到数据库中。(请注意这种方法是初步的,需要一些调整和调整)
//FROM class Application_Model_Tag
public function saveTags() {
//TODO implement instantiation of Domain Models instead of passing arrays to mappers
$trackMapper = new Music_Model_Mapper_Track();
$artistMapper = new Music_Model_Mapper_Artist();
$albumMapper = new Music_Model_Mapper_Album();
if (isset($this->_hash)) {
//see if track already exists by comparing hashs
$trackRow = $trackMapper->fetchByColumn('hash', $this->getHash());
//if track does not exist
if (is_null($trackRow)) {
//save the artist
$artistData = array(
'name' => $this->getArtist()
);
//see it the artist exists by name
$artistRow = $artistMapper->fetchByColumn('name', $this->getArtist());
//does artist exist?
if (is_null($artistRow)) {
$artistRow = $artistMapper->save($artistData);
}
//Save the Album Data
//does the album exist?
$albumRow = $albumMapper->fetchByColumn('name', $this->getAlbum());
//if yes
if (is_null($albumRow)) {
$albumData = array(
'name' => $this->getAlbum(),
'artist_id' => $artistRow->id,
'art' => $this->getAlbum() . '.jpg',
'year' => $this->getYear()
);
//get album row
$albumRow = $albumMapper->save($albumData);
}
//Save track data
$trackData = array(
'title' => $this->getTitle(),
'filename' => $this->getFilename(),
'path' => $this->getPath(),
'format' => $this->getFormat(),
'genre' => $this->getGenre(),
'artist_id' => $artistRow->id,
'album_id' => $albumRow->id,
'track' => $this->getTrack(),
'play_time' => $this->getPlay_time(),
'hash' => $this->getHash()
);
//save track data
$trackMapper->save($trackData);
}
} else {
return;
}
}
我希望这会有所帮助,请原谅这个例子的粗鲁。