2011-10-12 46 views
1

我试图在codeigniter中构造我的函数来保持事物的顶部。基本上我可以这样做:Codeigniter中的结构函数

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

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

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

这对我来说是最合理和最可读的解决方案。我尝试过,但对于PHP对象和类(还没有),我不太好。有没有简单的方法来实现这一点?还是有更实际的解决方案?谢谢!

回答

4

我认为你是在倒退。

您可以使用所需的常规功能创建多个模型,以扩展内置的CI_Model类。然后,您可以从这些新类继承特定的实现。

例如,假设你有一个数据库表名账户工作

首先,创建可扩展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一类,但具体到帐户表函数。

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();