views:

422

answers:

3

I just got started with CodeIgniter and am wondering will it slow things down if I put code like this in a loop.

    $data['title'] = 'the title';
    $data['content'] = 'blah blah blah';
    $this->load->view('result', $data);

I'm not entirely sure how CodeIgniter handles things, or PHP itself for that matter. For example if I did this. Would the file be read on each iteration?

    $data['title'] = 'the title';
    $data['content'] = 'blah blah blah';
    include 'result.php';

Also is it ok to load controls in a loop or am I missing something fundamental by putting a control in a loop? Thanks.

Additional info. I have search results for users' profiles... and I was thinking of making a slimmed down version of the profile view to display on the search results page. Would this be bad practice to use a view for that?

+2  A: 

Think about moving loop from controller to the view file (at controller you must prepare all data before load view file). You will have only one call for loading view file, and in the view file you can print out info in the loop cycle as you want.

Sergey Kuznetsov
+2  A: 

Loop in the view.

<div>
    <?php foreach ($this->user_model->get_users() as $users): ?>
        <p><?php echo $user->first_name;?></p>
        <p><?php echo $user->last_name;?></p>
    <?php endforeach; ?>
</div>

This sample directly gets data from the model which has been many times been discussed in the codeigniter forums.

Thorpe Obazee
I allowed myself to add the missing PHP tags...
Boldewyn
thanks Boldewyn
Thorpe Obazee
Please dont ever call a model from a view. Your controller should get the data from the model and then pass it to your view.
Ferdy
@Ferdy. That's the best way. I disagree that you shouldn't if the need arises. See: http://www.phpwact.org/pattern/model_view_controller.
Thorpe Obazee
I stand corrected, you convinced me that in some situations it is not as bad as I pictured it.
Ferdy
+3  A: 

I would not recommend calling your model from your view. This is not best practice when trying to keep to MVC framework standards. Call the model from your controller and pass the "users" array into the view as part of $data. Now you access the $users array just as a variable in the view. Similar to what you had, but this gets the access to the model back into the controller.

Controller

$data['title'] = 'the title';
$data['content'] = 'blah blah blah';
$data['users'] = $this->user_model->get_users();
$this->load->view('result', $data);

View

<?php foreach ($users as $user) {
    echo '<p>' . $user->first_name . '</p>';
    echo '<p>' . $user->last_name . '</p>';
}?>
Adam