1
我想創建一個後端,用於檢索某些信息並將其映射回對象。將SQL數據映射到對象
例如: 我有這個在我的模型類:
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Core_Product_Model extends CI_model {
//get the part id from an partnumber
public function getIdFromPartnumber($partnumber){
$this->db->select("id");
$this->db->from('part_list');
$this->db->where('part_number', $partnumber);
$query = $this->db->get();
return $query->result_object();
}
}
我處理這件事在我的控制器:
class Core_Product_Controller extends MX_Controller {
public function getAllCrosslinks(){
$response[] = array();
$response['error'] = false;
$partNumber = 100;
$output = $this->Core_Product_Model->getIdFromPartnumber($partnumber);
if(isset($output[0])){
$response['output'] = $output;
$response['valid'] = true;
}
echo json_encode($response);
}
}
這工作,但不是我想要的。我想檢索一切作爲一個對象。這不是一個問題,但是這樣做是一個好設計嗎?
一些的僞代碼:
類產品:
class Product {
private $productId;
private $stock;
function __construct($productId) {
$this->productId = $productId;
}
function getProductId(){
return $this->productId;
}
function stock(){
}
function setStock(Stock $stock){
$this->stock = $stock;
}
function getStock(){
return $this->stock;
}
}
型號:
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Core_Product_Model extends CI_model {
//get the part id from an partnumber
public function getIdFromPartnumber($partnumber){
$this->db->select("*");
$this->db->from('part_list');
$this->db->where('part_number', $partnumber);
$query = $this->db->get();
$result = $query->result_object();
//loop through result and map back to the Product class, save this to a array
//return the array
}
}
這是一個很好的方法做這樣?
在好的方法中,所有的業務邏輯必須內部控制器寫! – Saty
因此,映射到對象需要在控制器內完成? – da1lbi3
是的,所有在控制器內完成的映射! – Saty