Welcome Guest, Not a member yet? Register   Sign In
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

(This post was last modified: 02-13-2020, 04:45 PM by lahoussaine.)

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
#5

(02-13-2020, 04:43 PM)lahoussaine Wrote: 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

if you are in controller then you need something like this
$m="\App\Models".'\\'.$j['model'];               
$model=new $m();
Reply




Theme © iAndrew 2016 - Forum software by © MyBB