AQRC
AQRC

Reputation: 323

Kohana ORM. Usung Model object in View

I'm a novice in Kohana and whole ORM approach and can't find anywhere is this code acceptable in ORM or not. So, this function from Model returns an object

public function get_comments()
{
    $comments = ORM::factory('comment')->find_all();
    if ($comments)
    {
        return $comments;
    }
    else
        return array();
}

Controller sends this object to View

$content = View::factory('/index')
         ->bind('comments', $comments);
$comments = Model::factory('comment')->get_comments();
$this->response->body($content);

And here is the question: is it okay that I use object from Model in View like that:

 <?php foreach($comments as $comment): ?>
      <div>
          <h5><?php echo HTML::chars($comment->user->login); ?>:</h5>
          <?php echo HTML::chars($comment->text); ?>
      </div>
 <?php endforeach; ?>

Is it acceptable in ORM or should I somehow make an array from object and send it to View? Thanks

Upvotes: 0

Views: 258

Answers (1)

Scott Jungwirth
Scott Jungwirth

Reputation: 6675

Is it acceptable in ORM or should I somehow make an array from object and send it to View?

This is totally up to you to handle how you prefer.

Personally, I leave them as ORM objects in the view and take care not to do anything other than read access things in my views.

If you're working as part of a bigger team and want to be sure no one does anything than read from the models in the view, you can easily convert them to arrays or simple objects using json_encode/decode:

$simple_comments = json_decode(json_encode($comments)).

json serialization/unserialization may be slow for large sets of objects, in that case you can use ORM's as_array method:

$comments_as_arrays = array_map(function($c) { return $c->as_array(); }, $comments->as_array()).

Upvotes: 1

Related Questions