Welcome Guest, Not a member yet? Register   Sign In
Extending CI Loader to add method to return model, not globalize it
#1

[eluser]Unknown[/eluser]
Hi everyone,

My first post here. I have been using CI for 4 months and didn't realize until yesterday that all models were truly added to $this. I thought if you loaded a model in a model, it would only be available there but now understand it's available throughout the app.

Since I'd be accidentally overwriting models and model names all over the place, I came up with a way to extend the loader and return a model. Here's a copy of my post from Stackoverflow

----
Here's what I've decided to do, please comment if you have advice:

I've extended the CI Loader class:

Code:
<?php

class SSR_Loader extends CI_Loader
{
    function __construct()
    {  
        parent::__construct ();
    }  

/**
* Model Retriever
*
* Written by [email protected] to create and return a model instead of putting it into global $this
*
* Based on original 2.0.2 CI_Loader::model ()
*
*/
    function get_model($model)
    {  
        if (empty ($model))
        {  
            return;
        }  

        $name = basename ($model);

        if (!in_array($name, $this->_ci_models, TRUE))
        {  
            $this->model ($model);  
        }  

        $name = ucfirst($name);
        return new $name ();
    }  
}

Do any CI guru's see a problem with that before I invest time in changing my code a bit to accept the return obj, ala:

Code:
// in a controller:
public function test ($user_id=null)
{
    $this->_logged_in_user = $this->load->get_model ('/db/users');
    $this->_viewed_user    = $this->load->get_model ('/db/users');

    $this->_logged_in_user->load($this->session->userdata ('user.id'));
    $this->_viewed_user->load($user_id);
}

I could also do `private $_logged_in_user` to make it available in the controller but positively force it to be limited to just the current controller and not spill anywhere else, or I could just do `$_logged_in_user = $this->load->get_model ('/db/users');` and limit it to just the current method, which is probably what I'll do more often.

----

If you see a flaw in that plan, can you let me know? I'm not worried about having to initialize models in every controller/model (or, passing them in as a DI).




Theme © iAndrew 2016 - Forum software by © MyBB