0

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

2
  • I don't understand why you would need this extra method? Can't you do $comments = ORM::factory('comment')->find_all() directly in the controller?
    – kero
    Apr 16, 2015 at 10:34
  • If u use the find_all() method, use if (count($comments > 0)) instead of if ($comments).
    – mobal
    Apr 16, 2015 at 12:06

1 Answer 1

1

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()).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.