Welcome Guest, Not a member yet? Register   Sign In
Pass argument to model constructor while loading a model
#1
Lightbulb 
(This post was last modified: 01-15-2015, 12:00 PM by idealcastle.)

This was previously posted here. Long time ago. But it needs to be addressed if not already.
https://ellislab.com/forums/viewthread/115681/

I was just looking for this feature, and noticed this has yet to be published. Here is a good option.
I just copied it from what this guy has written up. though It could be done cleaner, any thoughts on doing this?

PHP Code:
function model($model$name ''$db_conn FALSE)
{
 
 //...
 
 //...
 
   $CI->$name = new $model();
 
   $CI->$name->_assign_libraries();
 
   $this->_ci_models[] = $name   


with

PHP Code:
function model($model$name ''$db_conn FALSE)
{
 
 //...
 
 //...

 
   if (func_num_args() > 3) {
 
       $refl = new ReflectionClass($model);
 
       $CI->$name $refl->newInstanceArgs(array_slice(func_get_args(), 3));
 
   } else {
 
       $CI->$name = new $model();
 
   }
 
   $CI->$name->_assign_libraries();
 
   $this->_ci_models[] = $name   



Example model with arguments in constructor:

PHP Code:
class ExampleModel extends Model {

 
   function __construct($param1$param2)
 
   {
 
       parent::Model();

 
       // do some with params
 
   }

 
   //...


Now you can pass yours parameters from controller to a models constructor after the first three arguments

PHP Code:
$this->load->model('ExampleModel'''FALSE$param1$param2); 


Feature like this does not ruin the integrity of the system, I dont see why it cant be done as a core. Again I'm sorry if this has already been brought up. Just something I needed, and this would of been a great help if was part of the core. Thanks.
Reply
#2

*Alternatively* Here is another option, I feel as though the above is complicated when it can be something more simple.

/system/core/Loader.php

PHP Code:
public function model($model$name ''$db_conn FALSE)


replace with

PHP Code:
public function model($model$name ''$db_conn FALSE$params = array())


then where the model is being loaded,

PHP Code:
$CI->$name = new $model(); 

replace with
PHP Code:
if (isset($params) && !empty($params)) {
 
 $CI->$name = new $model($params);
}
else {
 
 $CI->$name = new $model();

Reply




Theme © iAndrew 2016 - Forum software by © MyBB