Vizualni
Vizualni

Reputation: 381

What type of data should I send to view?

this question I've been asking myself since the day I started programming in MVC way. Should I send to view arrays filled with data or should I send it as on objects I retrieved from database? My model returns me data as objects. What would be the best way to create such a thing?

$new_data = $model->find_by_id(1);

echo $new_data->name; 

$new_data->name= "whatever";

$new_data->save();

For example. view.php

echo $object->name;

or

echo $array['name']

Language is php :).

Upvotes: 1

Views: 73

Answers (4)

jondavidjohn
jondavidjohn

Reputation: 62392

It does not matter how the data is formatted when it is sent to your view, as long as all you are doing with it, is displaying it in some form or another.

The test for view separation is based on logic, not data.

  • Are you changing the data inside the view?

This is a better question to ask in making sure you're data is ready to be passed to a view.

Upvotes: 5

Dan Lugg
Dan Lugg

Reputation: 20592

I created a Template class, which implements ArrayAccess, Iterator and Countable. This lets me use nested templates objects acting as arrays. For example my view might end up looking like:

<h1><?php echo $template['title']; ?></h1>
<?php foreach($template->post as $post): ?>
    <h2><?php echo $post['title']; ?></h2>
    <p><?php echo $post['body'] ?></p>
<?php endforeach; ?>

I can even call new pages, depending on what view files are associated with varying templates:

 <?php if($template->canRender('comments')): $template->comments->render(); endif; ?>

It's very useful this way. I've even begun adding formatting methods, by coercing all the data in the Template object to act as TemplateData objects, which have various formatting methods for simplicity:

<?php echo $template['secret_code']->asHash('md5'); ?>
<?php echo $template['title']->asCase('capitalize'); ?>

Upvotes: 1

greg0ire
greg0ire

Reputation: 23255

It's perfectly suitable to pass objects to your view. If you're starting to do complicate things in your view, then add a new method to your object, or do the thing in your controller, and pass a new variable to the view.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157828

you can send an array
as well as an object
whatever you want

Upvotes: 1

Related Questions