简体   繁体   English

Codeigniter中的结构函数

[英]Structure functions in Codeigniter

i´m trying to structure my functions in codeigniter to stay on top of things. 我正在尝试在codeigniter中构建我的函数以保持最佳状态。 Basicly i can make something like that: 基本上我可以做出类似的东西:

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

But of course i end up making and loading many files. 但当然我最终制作并加载了许多文件。 I´d rather structure it like my JS-code and extend my models: 我宁愿像我的JS代码一样构造它并扩展我的模型:

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

It´s the most logical and readable solution to me. 这对我来说是最合乎逻辑且最易读的解决方案 I tried it but i´m not that good with PHP objects and classes (yet). 我试过了,但我对PHP对象和类(但)并不是那么好。 Is there an simple way to achive this? 有没有一种简单的方法来实现这个目标? Or is there a more practical solution? 还是有更实用的解决方案? Thanks! 谢谢!

I think you are doing it backwards. 我认为你是倒退了。

You can create multiple models that extend the built in CI_Model class with the general functions you want. 您可以创建多个模型,使用所需的常规函数​​扩展内置的CI_Model类。 Then you can inherit from those new classes for specific implementations. 然后,您可以继承这些新类以进行特定实现。

For example, let's say you're working with a db table name Accounts 例如,假设您正在使用db表名称Accounts

First, create a class that extends CI_Model that contains general functions for working with a set of data (CI_DB_Result, an array of models, an array of arrays, etc). 首先,创建一个扩展CI_Model的类,该类包含用于处理一组数据的常规函数​​(CI_DB_Result,模型​​数组,数组数组等)。 Something like: 就像是:

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
  }
}

Next, create a class that extends table_model but with functions specific to the Accounts table. 接下来,创建一个扩展table_model的类,但具有特定于Accounts表的函数。

public class accounts_model extends table_model
{
  function __construct()
  {
    parent::__construct();
  }

  public function get_everything()
  {
    // whatever it takes to get everything...
  }
}

Finally, you can do stuff like... 最后,你可以做...

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

And if you have another model (my_model) you can also do: 如果你有另一个模型(my_model),你也可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM