Welcome Guest, Not a member yet? Register   Sign In
Model within a model
#11

(06-29-2021, 12:31 PM)LuxesR Wrote: Is it possible to include a model in the '__construct' and do the same with the other model?

PHP Code:
class Users_model extends \App\Models\BaseModel {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
 
$this->Settings model('Settings_model');
    }


PHP Code:
class Settings_model extends \App\Models\BaseModel {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
 
$this->Users model('Users_model');
    }


When I do this, I always get a 503 Service Temporarily Unavailable error. Is there a workaround for this?

because it will create infinite loop. like picture in picture in two mirror sided each other..
Reply
#12

That is not a good practice. However, to get past your current situation, you can do lazy loading of the needed models. That is, you do not load them on the needing models' instantiation. You can do something like this.
PHP Code:
class Settings_model extends \App\Models\BaseModel
{
    public 
$users;
    public function 
setUserModel(User_model $users)
    {
        
$this->users $users;
        return 
$this;
    }
}

// When creating the models, you can this;
$users model('Users_model');
$settings model('Settings_model');

// now your settings model has an instance of users model
// you can do the same with users
// but beware that this may cause memory leaks
$settings->setUserModel($users); 
Reply
#13

Okay. It looks like that this is not an option what I'm asking. But how about I include the model every time there is a new function inside a model? Is this oke or will it also eventually give a memory leak if there are to many?
For example like this:
PHP Code:
namespace App\Models;
use 
CodeIgniter\Model;
class 
Settings_model extends \App\Models\BaseModel {
    
    function 
tempFunction(){
        
$this->Users model('Users_model');
        
$users $this->Users->get_all_users();
    }


PHP Code:
namespace App\Models;
use 
CodeIgniter\Model;
class 
Users_model extends \App\Models\BaseModel {
    
    function 
tempFunction(){
        
$this->Settings model('Settings_model');
        
$settings $this->Settings->get_settings();
    }


I know that this means that it includes a model everytime in every function, but at least I can get the application running on CI4 and I can fix parts in the future.

By the way, why is the autoload for models from CI3 gone? I have some applications having a lot of models inside the autoload and it still runs really fast. You did not even notice it when loading it.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB