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";
$ne开发者_如何学编程w_data->save();
For example. view.php
echo $object->name;
or
echo $array['name']
Language is php :).
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.
you can send an array
as well as an object
whatever you want
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.
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'); ?>
精彩评论