• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Load Dynamic Model

#1
Hello 

I would like use a dynamic model, i want use loop to load multiple model dynamically, in CI3 work fine and in CI4 doesn't  work 
this is an example 

$array = array("Roles");
foreach ($array  as $key => $value) {
                
                $UsersModel = new RolesModel();  // this work fine 
                $module = $key.'Model';
                $module = new $module(); // this return error : Class 'RolesModel' not found
                        
}

can you help me !
Reply

#2
Add the "use" statement above your class.

I.e.

use App\Models\RolesModel;

class x extends Controller {

}
Reply

#3
(02-13-2020, 01:49 PM)falko Wrote: Add the "use" statement above your class.

I.e.

use App\Models\RolesModel;

class x extends Controller {

}


This is top of my Controller :


Code:
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\UsersModel;
use App\Models\RolesModel;
use App\Models\PermissionsModel;


class BaseController extends Controller
{

so when i use this syntax 
Code:
$UsersModel = new RolesModel();
work fine  without any problems !!!
wheen 


Code:
$variable = "NameOfModel";
$UsersModel = new $variable();
not work 

any idea !!
Reply

#4
finally i found a solution for this problem
we have to must declare the full namespace path of a class

Code:
namespace App\Models
use App\Models\MyModel
...
case 1 :
$mymodule = new MyModel(); // work fine

case 2 :
$module = "MyModel";
$mymodule = new $module();  // Error not found

case 3:
$module = "App\\Models\\MyModel";
$mymodule = new $module();              // work fine

for help 
 
thx
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.