我一直在使用CodeIgniter for PHP一段时间了,虽然我现在要使用Laravel,但如果我重新启动我正在进行的项目,我现在与CodeIgniter密切相关。
我有一个问题/疑问。在探索了Go(GoLang)等其他语言甚至是一些Ruby之后,我发现了一些关于PHP的奇怪之处,也许是特定于CodeIgniter的。
模型不是真正的模型..它们更像是数据库的接口,只是为了提取数据,这几乎看起来像是浪费和不必要。
我试图弄清楚是否更好的做法是定义模型并在拉动数据并像普通对象一样访问后为其分配每个变量。像这样:
class Product_m extends CI_Model {
public $name;
private $_table = 'products';
public function __construct()
{
parent::__construct();
}
public function get($id)
{
$query = $this->db->get_where($this->_table, 'id', $id); //this is off memory.. just an example
$result = $query->result();
$this->name = $result[0]->name;
}
public function get_all($shop_id)
{
$query = $this->db->get($this->_table);
$result = $query->result();
// loop and build array of objects...
}
}
对于返回像$this->get_all()
这样的对象数组的函数,这不会起作用,因为在CI中加载模型一次。
所以我想我也许可以创建一个单独的类(或扩展类),它实际上就像一个结构并定义了类。这样我就可以在想要创建对象数组时实例化该类,如果我想要将返回对象添加到我的控制器,就像返回$this
一样。
class Sp_Product {
public $id = 0;
public $name;
public $images = array();
}
class Product_m extends CI_Model {
private $_table = 'products';
private $_model = 'Sp_Product';
public function __construct()
{
parent::__construct();
}
public function get($id)
{
$query = $this->db->get_where($this->_table, 'id', $id); //this is off memory.. just an example
$result = $query->result();
$product = new $this->_model;
$product->id = $id;
$product->name = $result[0]->name;
return $product;
}
public function get_all($shop_id)
{
$query = $this->db->get($this->_table);
$result = $query->result();
$products = array();
foreach($result as $p)
{
$product = new $this->_model;
$product->id = $p->id;
$product->name = $p->name;
$products[] = $product;
}
return $products;
}
}
我测试了这个并且它有效。以下是我认为的优点和缺点:
Sp_Product_Image
个对象中的每个图片加载Sp_Product
。我觉得我可能已经超越了CodeIgniter,而这正是它显示出它的弱点所在。我对其他建议持开放态度,如果我的术语混淆了,请告诉我。