更好的CodeIgniter模型结构?

时间:2015-07-13 06:18:17

标签: php codeigniter oop model-view-controller model

我一直在使用CodeIgniter for PHP一段时间了,虽然我现在要使用Laravel,但如果我重新启动我正在进行的项目,我现在与CodeIgniter密切相关。

PHP模型设计

我有一个问题/疑问。在探索了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;
    }

}

您怎么看?

我测试了这个并且它有效。以下是我认为的优点和缺点:

积极因素

  1. 我可以将我的应用程序模型分别设置为我的数据库模型。这意味着如果我在我的数据库中更改列名,那么我不需要在我的应用程序中更改尽可能多的代码。
  2. 这将有助于更清晰的编程实践。
  3. 它提供了一些结构和一致性。
  4. 如果您因某些原因无法访问数据库,则会消除歧义。
  5. 我可以在我的模型中使用其他类类型。例如,如果我有嵌套数据模型:product>图片。我可以为Sp_Product_Image个对象中的每个图片加载Sp_Product
  6. 否定

    1. 安装需要额外的工作。
    2. 使用此方法可能会使用额外的内存,因为模型将被加载以及返回一个对象或一组新对象。 对此有何想法和建议?
    3. 我觉得我可能已经超越了CodeIgniter,而这正是它显示出它的弱点所在。我对其他建议持开放态度,如果我的术语混淆了,请告诉我。

1 个答案:

答案 0 :(得分:-1)

对于get_where()方法,CI期望关联数组作为第二个参数。所以:

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Reference。 顺便说一句,我使用的MY_Model具有很多功能,可以用于各种任务。