Manipulate data in the controller or model?

I have retrieving a date and time from the database in this format:

2017-11-25 21:08:48

What I had done before using MVC was:

$date = date_create($row['article_date']);
$article_date = date_format($date, "d F Y - h:ia");
echo $article_date;

Open in new window


I am not sure how to do this using MVC.

My model:

	public function getPosts() {
		
		$this->db->query("SELECT `id`, `title`, `article`, `article_date`, `slug` FROM `news`");
		$results = $this->db->resultSet();
		return $results;
	}

Open in new window


The controller:

      
public function index() {
		
		$posts = $this->postModel->getPosts();
		
		$data = [
			
			'posts' => $posts
		];
		
		$this->view('posts/index', $data);
	}

Open in new window


Then in the view I would have:

<?php foreach ($data['posts'] as $post){  ?>
  // some html here
<?php echo $post->article_date; ?>

Open in new window


I can't just use date_format on the $post->article_date without first using date_create. But I just am not sure where I would use date_create i.e.: would you do that in the model or controller before passing to the view?
LVL 1
Black SulfurAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
Many times you'll have an init() function/step which occurs outside the M or V or C, to setup your runtime environment.

Think of this as IMVC.

Just collect all your initialization into an init() function or better _init().
0
Steve BinkCommented:
In MVC, every piece of work is categorized into one of three areas: model, view, controller.

The controller is like a routing mechanism.  It decides where data is coming from and where the data should go.  Any logic necessary to decide which model or view is appropriate should be here.

The model is the data source.  It is responsible for connecting to your raw repository (the database), retrieving data appropriate to the request, and transforming into a consumable form by implementing business logic.  It is an interpreter between your business objects and raw storage.

The view is the presentation layer.  It is responsible for manipulating the data into a presentable form, deciding how presentation will occur, and is responsible for generating the presented output.

I understand your question as "I have a piece of data to display.  Where do I put the commands to prepare it for display?"  My answer is the view.  Once the controller pushes the model into the view, the view should run any commands necessary to format the data as desired.  

While I consider the call to date_format() definitely a view responsibility, one could argue that the creation of the Date object is a model function.  If your entire application is dependent on having a Date object instead of a timestamp (meaning, you will never use the raw data - only the well-formed Date object), then it would be appropriate to have the model do that work.
1
David FavorLinux/LXD/WordPress/Hosting SavantCommented:
If you'd like to stick with MVC completely, then you can always build inline initialization... like this...

if (! isset(something)) {
   set something
}

Open in new window

0
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Black SulfurAuthor Commented:
Thank you for your comments. So, in the view would I do this?

$date = date_create($row['article_date']);
$article_date = date_format($date, "d F Y - h:ia");

<p>Some paragraph text here</p>
  <h4>This contact was updated on <?php echo $article_date; ?></h4>
<p>A second paragraph here</p>

Open in new window


And secondly, if I wanted the model to handle it, how would I get it out and make use of it in the controller?

public function getPosts() {
		
		$this->db->query("SELECT `id`, `title`, `article`, `article_date`, `slug` FROM `news`");
		$results = $this->db->resultSet();
		return $results;
                // need to do the date_create here somehow?
	}

Open in new window


Before using MVC I would have just grabbed the database record and then used $article_date wherever I wanted to.

$date = date_create($row['article_date']);
$article_date = date_format($date, "d F Y - h:ia");

Open in new window

0
Steve BinkCommented:
Your example code for the view is fine.  You could also approach it this way:
<?php
$date = new DateTime($row['article_date']);
?>
<p>Some paragraph text here</p>
  <h4>This contact was updated on <?php echo echo $date->format('d F Y - h:ia'); ?></h4>
<p>A second paragraph here</p>

Open in new window


Based on what you've shown of your model, I would suggest that the view is the proper place for this.  In many frameworks, the model is not just a simple pathway to fetching the data - it also binds the data to an object (usually itself) after whatever manipulation is necessary to make the raw data consumable.  Since your model is simply returning the raw row, it would be out of place for your model to manipulate one field.  The better strategy here is to assume the row data is raw, and allow the view to prepare it as necessary.
0
Black SulfurAuthor Commented:
Thanks Steve. That makes sense but my only concern is that aren't you now mixing up your presentation and logic code? I had this idea that what I put in the view should be almost perfect and not still have to manipulate the code in the view. If this is good, standard practice then so be it, I will follow that for sure. But I was just concerned that I wouldn't be 'separating concerns'.
0
Black SulfurAuthor Commented:
Oh, one last thing. Would you be able to please show me what you would do differently in the model code I posted? I am referring to what you said :

In many frameworks, the model is not just a simple pathway to fetching the data - it also binds the data to an object (usually itself) after whatever manipulation is necessary to make the raw data consumable.
0
Steve BinkCommented:
>>> Before using MVC I would have just grabbed the database record and then
>>> used $article_date wherever I wanted to.

That raises a wonderful example of what I referenced in my last reply.  In (what I think of as) a standard MVC architecture, your objects might look something like this:
/* The controller */
class MyController {
  public function execute() {
    $model = new MyModel($Environment);
    $view = new MyView($model);
  }
}

/* The model */
class MyModel {
  public function __construct($Environment) {
    $this->params = $Environment;
    $this->bind();
  }

  public function bind() {
    $row = self::getData();

    // Ideally, this is where you would manipulate the raw data to put it a universally
    // consumable state.
    $this->field1 = $row['field1'];
    $this->field2 = $row['field2'];
    $this->theDate = new Date($row['datefield']);
  }
}

/* the View */
class MyView {
  public function __construct($model) {
    $this->data_object = $model;
    // Probably something here to pick the template
    // Then we make sure the data looks how we want
    $this->format();
  }

  public function format() {
    $this->theDate = $this->data_object->format('d F Y - h:ia');
  }
}

Open in new window


Note that the model doesn't actually return anything.  The model object itself becomes the data to be consumed.  The view is then free to leverage whatever presentation-layer formatting it needs:
<p>Some paragraph text here</p>
  <h4>This contact was updated on <?php echo $this->theDate; ?></h4>
<p>A second paragraph here</p>

Open in new window

0
Steve BinkCommented:
Note that the above is *very* simple framework, mostly focused on the activity of the model.  If you're interested in seeing an actual implementation along these lines, I recommend you explore the Joomla framework.  That framework has a very nice strategy for MVC, with virtually everything keyed off of naming conventions, and a few environment/request variables (e.g., the MVC section is dictated by the "option" $_GET/$_POST parameter).  If you take the time to dissect how the *Controller, *View, and *Model base classes function, it will give you a great tutorial in basic MVC.
1
Black SulfurAuthor Commented:
Hmm. I think I am confusing myself here. I don't want to draw  this out so for now, until I get more practice and a better understanding of MVC, is it safe to say that any data manipulation I do can just be done in the view? That seems to be the simplest way for me right now. I believe you did say that, but I am just confirming that...
0
Steve BinkCommented:
Yes.  For now, prepping the date for display can be done entirely in the view.  As I mentioned earlier, the only reason you would want to do some of the prep in the model is if your *entire* application would be expecting it.  I.e., if you are always going to create a DateTime object before using the date stored in the database, then it makes sense to always create the object when you load the data.  

As you progress through making your app, you'll begin to notice these common tasks that you have to do all the time.  After awhile, you'll get tired of having to do them all the time, and just want them done.  That's when you'll move them to the model.  :)
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Black SulfurAuthor Commented:
Perfect, thanks!
0
Steve BinkCommented:
I just noticed I missed this comment:

>>> I had this idea that what I put in the view should be almost perfect and
>>> not still have to manipulate the code in the view. If this is good, standard
>>> practice then so be it, I will follow that for sure. But I was just concerned
>>> that I wouldn't be 'separating concerns'.

That is the "right" goal, and illustrates one of the points I was trying to stress.  

While you're probably using this model to feed this one view, it is entirely possible that, in the future, you will have multiple views capable of displaying the same model.  It may be that not all of the views will have a need to translate that raw date into a DateTime object; for some views, the DateTime object may be an obstacle.  Most likely they will all be able to use it (DateTime is a fairly benevolent manipulation), but I could imagine circumstances where the raw data would be desired.  Then again, it could be that every time you want to display that date field, it is just easier (or even necessary) to create a DateTime object.  The pattern of your actual consumption of the data will dictate what manipulations you want the model to apply.  As is usually the case, though, those patterns are not readily visible until you have gone a bit down the road.  I would not worry too much about "getting it right the first time" - that's often an obsession with us developers which is just as often an obstacle to progress.  Some things you just can't get right until the application shows you what "right" is going to look like.

Good luck!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.