views:

90

answers:

3

I would like to add some PHP to my Codeigniter view, for, say, a dynamic date in the footer. What is the very best way to manage this?

+2  A: 

If you are going to be passing data to the view, then populate the $data array in the controller:

$data = array(
  'date' => $myDate
);
$this->load->view('myview', $data);

Then in your view just add some PHP to write it out. For example:

<?php echo($date); ?>
Justin Ethier
This isn't actually anything stopping you from putting whatever PHP code into the view you want, other than the fact that you should only be displaying things in the view. As Justin says, do as much of your processing in the controller (or model) as you can.
Blair McMillan
If I use this method, I have to carry the code that generates the data around to every Model function that uses the view.
mmcglynn
Controllers (not models) load the views, and a controller can load multiple models. So you can just use a single model to generate the same piece of data for each controller.
Justin Ethier
+5  A: 

There's nothing wrong with having PHP in your views. I use PHP in my views all the time for things like looping through arrays and creating ordered lists, etc. IMO, MVC is not about separating HTML from PHP, it's about separating business logic and display logic.

There are many different interpretations and implementations of MVC, so some people will disagree with me, and that's fine. Decide how you want to use MVC and be consistent throughout your project.

bradym
A: 

For your view, you can either pass data to it via a controller or even you can put the php code directly in your view file. There is no restriction on that. However, to keep things consistent it is always good idea to put as much php code in controllers as possible and view should contain mostly the pure html/css/js code but as i said there is nothing wrong even if you put php code in your view files.

Sarfraz