简体   繁体   English

DataMapper for Codeigniter:是否可以一次实例化模型对象并重新使用?

[英]DataMapper For Codeigniter: Possible To Instantiate Model Object Just Once and Reuse?

Not trying to spam or advertise here, I value this community and the people that gladly give up their time to answer questions (like myself). 我不打算在这里发送垃圾邮件或做广告,我很重视这个社区和乐于放弃时间回答问题的人们(例如我自己)。 I have built an authentication library for Codeigniter called WolfAuth. 我为Codeigniter构建了一个名为WolfAuth的身份验证库。 It currently relies on DataMapper for all database interaction, until further notice. 当前,它依赖于DataMapper进行所有数据库交互,直到另行通知。

Each function currently uses code along the lines of the following. 当前,每个函数都使用以下代码。

$u = new User;
$u->get_by_id($user_id);

if ( $u->exists() )
{  
    // Do user stuff here  
}

I'm not entirely sure how PHP handles object instantiation, but surely doing this in 50 functions plus can't be good for performance, and if not, adds unnecessary object instantiation. 我不完全确定PHP如何处理对象实例化,但是肯定要用50个函数执行此操作,而且性能不好,否则就添加不必要的对象实例化。 Is it possible to have a global instantiation of each DataMapper model object I am using and re-use in each function? 是否可以对我正在使用并在每个函数中重复使用的每个DataMapper模型对象进行全局实例化?

So something like the following. 所以像下面这样。

class Someclass {

    protected $user;
    protected $group;
    protected $roles;

    public function __construct()
    {
        $this->user  = new User;
        $this->group = new Group;
    }

    public function the_user($user_id)
    {
        $user = $this->user->get_by_id($user_id);

        if ( $user->exists() )
        {
            echo "The user exists!";
        } 
    }

}

Am I just being extremely picky here, or is what I am asking possible and probably the better way to do things for such a large library like I've built? 我只是在这里非常挑剔,还是我想问的是可能的,也许是对像我这样建成的大型图书馆做事的更好方法?

Yes, you can pass objects as arguments in php. 是的,您可以在php中将对象作为参数传递。

class Someclass {

protected $user;
protected $group;
protected $roles;

public function __construct()
{
    $this->user  = new User();
    $this->group = new Group();
}

public function get_user($user_id)
{
    if (empty($this->user->id))
    {
        $user = $this->user->get_by_id($user_id);
    }
    else
    {
        $user = $this->user;
    }
    if ( $user->exists() )
    {
        prove_user_exists($user);
        return $user;
    }
    else
    {
        show_error('No User Found');
    }
}

public function prove_user_exists($user)
{
    log_message('info', $user->id);
}

Then, you can just call get_user($user_id) when you need the user - if the user has already been found, then you won't have to call the db again. 然后,您可以在需要用户时调用get_user($ user_id)-如果已经找到该用户,则不必再次调用该数据库。

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

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