Welcome Guest, Not a member yet? Register   Sign In
Load model with a constructer - possible?
#4

[eluser]phpoet[/eluser]
That is very interesting. It's almost like CI Models are sort of more like pseudo-controllers or database controllers. The documentation for Models has a function that returns an array of objects representing rows in a database. If all you need to do is access the data in a table row, this works great. But when you need to perform a calculation on the data it seems like things get a little funny.

Suppose, like you said, you have a CI model for Users and you have a database table that holds all the data for the users such as name, and date of birth. Then you want to list all of the users and their ages. The age, however, needs to be calculated based on the date of birth. I'd want to create a function in the model to calculate age. Then I would have the controller load up an array of User models and pass that array of Users to the view. In the view, I would loop through the array and do something like...

Code:
<?php foreach($users as $user) ?>
  <p>&lt;?= $user->name ?&gt; is &lt;?= $user->calculate_age() ?&gt; years old.</p>
&lt;?php endforeach; ?&gt;

That seems like a more reasonable approach than only having one User instance and reloading it's data attributes for each user in the list. If I understand you correctly, it seems like you would suggest having the controller load an array of User id numbers and pass the array of ids to the view. Then, in the view, doing something like this...

Code:
&lt;?php foreach($users as $user_id) ?&gt;
  &lt;?php $this->User->load_from_database($user_id); ?&gt;
  <p>&lt;?= $user->name ?&gt; is &lt;?= $user->calculate_age() ?&gt; years old.</p>
&lt;?php endforeach; ?&gt;

The problem I have with this approach is that it hits the database much more. First, there is a query to get all the User ids. Then another query for each User in the system. What are your thoughts about that? Have I misunderstood the recommendation of having only one instance that represents a type of data?


Messages In This Thread
Load model with a constructer - possible? - by El Forum - 08-26-2008, 02:42 PM
Load model with a constructer - possible? - by El Forum - 08-27-2008, 01:58 PM
Load model with a constructer - possible? - by El Forum - 08-27-2008, 02:27 PM
Load model with a constructer - possible? - by El Forum - 08-27-2008, 03:08 PM
Load model with a constructer - possible? - by El Forum - 08-27-2008, 11:05 PM
Load model with a constructer - possible? - by El Forum - 08-28-2008, 08:08 AM
Load model with a constructer - possible? - by El Forum - 08-28-2008, 09:58 AM
Load model with a constructer - possible? - by El Forum - 08-28-2008, 12:59 PM



Theme © iAndrew 2016 - Forum software by © MyBB