Welcome Guest, Not a member yet? Register   Sign In
Constructors and Parametes
#1

[eluser]uris[/eluser]
I want to create a model that initializes some default values when it is initialized.

For instance, if my model is people:

Code:
class PeopleModel extends Model
{
  var $firstname;
  var $lastname

   function __construct($firstname,$lastname)
   {
     $this->firstname = $firstname;
     $this->lastname = $lastname;
   }

   function createNew()
   {
      //Insert $lastname and $firstname into database.
    }
}

And on the controller I want to be able to do call the model and pass some variables through the constructor:

Code:
$this->load->model('PeopleModel', 'Harry','Potter');
$this->PeopleModel->createNew();

Can this be done?
#2

[eluser]maadmac[/eluser]
Why not just:

Code:
$this->load->model('PeopleModel');
$this->PeopleModel->createNew('Harry', 'Potter');

if you're going to use the 'createNew' function anyway? You wouldn't need to declare the variables at all, really...
#3

[eluser]wiredesignz[/eluser]
Sadly Models don't allow for initial parameters other than $name and $db_conn.

But you can pass initial parameters as you load a Library.

$this->load->library('lib_name', $init_params)
#4

[eluser]thurting[/eluser]
Just 'require_once' the model file and use the 'new' operator. Sometimes the framework gets in the way - don't be afraid to work outside of its conventions.
#5

[eluser]uris[/eluser]
[quote author="maadmac" date="1197456613"]Why not just:



if you're going to use the 'createNew' function anyway? You wouldn't need to declare the variables at all, really...[/quote]

Well, I would use createNew only if I want to do precisely that. But if I already have some records in the database, and all I want to do is to perform some operations on those records I would then pass those parameters to the constructor. Then the constructor would assign them to a variable and I would operate on those variables. Until I am done with my operations, then I would insert into database.
#6

[eluser]eggshape[/eluser]
Well how are $firstname and $lastname assigned? If you're assigning from a form, you don't need to pass the parameters:

Code:
function __construct()
   {
     $this->firstname = $this->input->post('firstname');
     $this->lastname = $this->input->post('lastname');
   }

However, I would advise against this because you have not validated the form fields. Alternatively, you can instantiate the model (load it), run validation, and then call your method createNew(), like how MaadMac suggested. Note, you can do all this in the constructor if you wish.




Theme © iAndrew 2016 - Forum software by © MyBB