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