【问题标题】:Structure functions in CodeigniterCodeigniter 中的结构函数
【发布时间】:2011-10-12 12:20:06
【问题描述】:

我正在尝试在 codeigniter 中构建我的函数以保持领先地位。基本上我可以做这样的事情:

$this->my_model->get_everything();
$this->my_model_db->write_all();

当然,我最终会制作和加载许多文件。我宁愿像我的 JS 代码那样构建它并扩展我的模型:

$this->my_model->db->write_all();

这对我来说是最合乎逻辑和可读性的解决方案。我试过了,但我对 PHP 对象和类还不是很好(还)。有没有一种简单的方法来实现这一点?还是有更实用的解决方案?谢谢!

【问题讨论】:

    标签: php codeigniter model


    【解决方案1】:

    我认为你是在倒退。

    您可以创建多个模型来扩展内置的 CI_Model 类,并使用您想要的通用功能。然后,您可以从这些新类中继承特定的实现。

    例如,假设您正在使用数据库表名Accounts

    首先,创建一个扩展 CI_Model 的类,其中包含用于处理一组数据的通用函数(CI_DB_Result、模型数组、数组数组等)。比如:

    abstract class table_model extends CI_Model
    {
      function __construct()
      {
        parent::__construct();
      }
    
      public function write_all()
      {
        // do some stuff to save a set of data
        // maybe add some logging in here too, if it's on development
        // and how about some benchmarking for performance testing too
        // you get the idea
      }
    }
    

    接下来,创建一个扩展 table_model 的类,但具有特定于 Accounts 表的函数。

    public class accounts_model extends table_model
    {
      function __construct()
      {
        parent::__construct();
      }
    
      public function get_everything()
      {
        // whatever it takes to get everything...
      }
    }
    

    最后,你可以做...

    $this->account_model->get_everything();
    $this->account_model->write_all();
    

    如果你有另一个模型(my_model)你也可以这样做:

    $this->my_model->get_just_a_few_things();
    $this->my_model->write_all();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多