0

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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); ?>

3 Comments

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.
If I use this method, I have to carry the code that generates the data around to every Model function that uses the view.
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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.