I have a base class with 3 sub ones: Item <-- Book, MusicCD, Software
They have some common and different properties but in the view I want to get a mixed list of them and show in one table:
Title Price Volume Author Artist Edition Version
So I have done this:
Classes:
abstract class Item {
protected $id;
protected $title;
protected $price;
function getTitle() { return $this->title; }
function getPrice() { return $this->price; }
function getAuthor() { return ''; }
function getEdition() { return ''; }
function getVolume() { return ''; }
function getArtist() { return ''; }
function getVersion() { return ''; }
}
class Book extends Item {
private $author;
private $edition;
private $volume;
function getAuthor() { return $this->author; }
function getEdition() { return $this->edition; }
function getVolume() { return $this->volume; }
}
class MusicCd extends Item {
private $artist;
private $volume;
function getArtist() { return $this->artist; }
function getVolume() { return $this->volume; }
}
class Software extends Item {
private $version;
function getVersion() { return $this->version; }
}
View:
<?php
// The controller pass items to view
$items = $this->items;
?>
<table>
<tr>
<th>Title</th><th>Price</th><th>Volume</th><th>Author</th><th>Artist</th><th>Edition</th><th>Version</th>
</tr>
<?php
foreach ($items as $i) :
?>
<tr>
<td><?=$i->getTitle()?></td>
<td><?=$i->getPrice()?></td>
<td><?=$i->getVolume()?></td>
<td><?=$i->getAuthor()?></td>
<td><?=$i->getArtist()?></td>
<td><?=$i->getEdition()?></td>
<td><?=$i->getVersion()?></td>
</tr>
<?php
endforeach;
?>
</table>
Here the question: I feel that the classes seem not good enough because if there are more subtypes appears, chance that I have to modify the Item
class. Please help me improve that.
Item
a__toString
method and just writeecho $i . "\n";
orecho "$i\n";
. – Brythan Dec 17 '14 at 10:40