【问题标题】:codeigniter instance of model class模型类的codeigniter实例
【发布时间】:2011-06-13 15:30:12
【问题描述】:

我正在使用 codeigniter 开发一个网站。现在,通常当你在 codeigniter 中使用一个类时,你基本上把它当作一个静态类来使用。例如,如果我领导一个名为“用户”的模型,我会首先使用

$this->load->model('user');

然后,我可以调用该用户类上的方法,例如

$this->user->make_sandwitch('cheese');

在我正在构建的应用程序中,我想要一个 UserManagement 类,它使用一个名为“用户”的类。

这样,例如我可以

$this->usermanager->by_id(3);

这将返回 id 为 3 的用户模型的 实例。 最好的方法是什么?

【问题讨论】:

  • 最好的方法是使用 ORM。 Doctrine 是流行的一种,有一些关于它与 CodeIgniter 集成的教程
  • @bassneck 感谢您的建议。我可能不会在我当前的项目中使用它,但我肯定会研究教义,乍一看它看起来很棒。

标签: php codeigniter model instance


【解决方案1】:

CI 中的模型类与其他语法中的模型类并不完全相同。在大多数情况下,模型实际上是某种形式的普通对象,带有与之交互的数据库层。另一方面,对于 CI,Model 表示返回通用对象的数据库层接口(它们在某些方面有点像数组)。我知道,我也觉得自己被骗了。

所以,如果你想让你的模型返回不是 stdClass 的东西,你需要包装数据库调用。

所以,这就是我要做的:

创建一个包含您的模型类的 user_model_helper:

class User_model {
    private $id;

    public function __construct( stdClass $val )
    {
        $this->id = $val->id; 
        /* ... */
        /*
          The stdClass provided by CI will have one property per db column.
          So, if you have the columns id, first_name, last_name the value the 
          db will return will have a first_name, last_name, and id properties.
          Here is where you would do something with those.
        */
    }
}

在usermanager.php中:

class Usermanager extends CI_Model {
     public function __construct()
     {
          /* whatever you had before; */
          $CI =& get_instance(); // use get_instance, it is less prone to failure
                                 // in this context.
          $CI->load->helper("user_model_helper");
     }

     public function by_id( $id )
     {
           $q = $this->db->from('users')->where('id', $id)->limit(1)->get();
           return new User_model( $q->result() );
     }
}

【讨论】:

  • 您不需要手动实例化 User_model。您可以将模型类名称作为 result() 的参数传入,它将返回一个新实例,其中填充了数据库中的数据。 $q->result('User_model')
【解决方案2】:

使用抽象工厂模式甚至数据访问对象模式来完成您需要的工作。

【讨论】:

    【解决方案3】:
    class User extend CI_Model 
    {
        function by_id($id) {
            $this->db->select('*')->from('users')->where('id', $id)->limit(1);
            // Your additional code goes here
            // ...
            return $user_data;
        }
    }
    
    
    class Home extend CI_Controller
    {
        function index()
        {
            $this->load->model('user');
            $data = $this->user->by_id($id);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2011-05-26
      • 2013-07-09
      • 1970-01-01
      • 2014-01-30
      • 2011-10-28
      相关资源
      最近更新 更多