我经常遇到如下代码(参考
Slim tutorial
在
github
)
ticketmapper.php文件
class TicketMapper extends Mapper
{
public function getTickets() {
$sql = "SELECT t.id, t.title, t.description, c.component
from tickets t
join components c on (c.id = t.component_id)";
$stmt = $this->db->query($sql);
$results = [];
while($row = $stmt->fetch()) {
$results[] = new TicketEntity($row);
}
return $results;
}
/**
* Get one ticket by its ID
*
* @param int $ticket_id The ID of the ticket
* @return TicketEntity The ticket
*/
public function getTicketById($ticket_id) {
$sql = "SELECT t.id, t.title, t.description, c.component
from tickets t
join components c on (c.id = t.component_id)
where t.id = :ticket_id";
$stmt = $this->db->prepare($sql);
$result = $stmt->execute(["ticket_id" => $ticket_id]);
if($result) {
return new TicketEntity($stmt->fetch());
}
}
public function save(TicketEntity $ticket) {
$sql = "insert into tickets
(title, description, component_id) values
(:title, :description,
(select id from components where component = :component))";
$stmt = $this->db->prepare($sql);
$result = $stmt->execute([
"title" => $ticket->getTitle(),
"description" => $ticket->getDescription(),
"component" => $ticket->getComponent(),
]);
if(!$result) {
throw new Exception("could not save record");
}
}
}
票务.php
class TicketEntity
{
protected $id;
protected $title;
protected $description;
protected $component;
/**
* Accept an array of data matching properties of this class
* and create the class
*
* @param array $data The data to use to create
*/
public function __construct(array $data) {
// no id if we're creating
if(isset($data['id'])) {
$this->id = $data['id'];
}
$this->title = $data['title'];
$this->description = $data['description'];
$this->component = $data['component'];
}
public function getId() {
return $this->id;
}
public function getTitle() {
return $this->title;
}
public function getDescription() {
return $this->description;
}
public function getShortDescription() {
return substr($this->description, 0, 20);
}
public function getComponent() {
return $this->component;
}
}
我当前的实践不使用实体类,而我的映射器方法只返回如下所示的stdclass:
class TicketMapper extends Mapper
{
public function getTickets() {
$sql = "...";
$stmt = $this->db->query($sql);
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
public function getTicketById($ticket_id) {
$sql = "...";
$stmt = $this->db->prepare($sql);
$result = $stmt->execute(["ticket_id" => $ticket_id]);
return $stmt->fetch(); //Assuming my PDO is configured to return an object only
}
public function save($ticket) {/* no change */}
}
为什么数据库结果经常包装在某个实体类中?有什么标准可以决定是否这样做吗?