Kohana/ORM - Assign relations to views
I have an object in a controller's method:
$post = ORM::factory('post', array('slug' => $slug);
that is sent to the view:
$this->template->content = View::factory('view')->bind('post', $post);
I've created 1-n relation between post and comments. So good so far.
The main issue is: how should I pass post comments to the view? Currently I'm getting them in the view ($pos开发者_运维技巧t->comments->find_all()
) but I don't feel it's the best method (and not matching MVC standards in my humble opinion). I was also thinking about assigning them to the property in the controller ($post->comments
) however I get an error about undefined property (which makes sense to me).
How would you recommend to solve that issue?
Why not grab the comments in the controller and pass them to the view for presentation? At least that's how I'd go about this.
$post = ORM::factory('post', array('slug' => $slug));
$comments = $post->comments->find_all();
$this->template->content = View::factory('view')->bind('comments', $comments);
In regards to your multiple pages comment, which I assume you mean posts... This is what I would usually do.
$posts = ORM::factory('post', array('slug' => $slug))->find_all();
$view = new View('view');
foreach ($posts as $post) {
$view->comments = $post->comments;
$this->template->content .= $view->render();
}
Though this may not be the most resource friendly way to accomplish this, especially if you're working with many posts. So passing the posts to the view and then doing the foreach loop inside the view may be a better way to go about this.
$posts = ORM::factory('post', array('slug' => $slug))->find_all();
$this->template->content = View::factory('view')->bind('posts', $posts);
Though I also don't necessarily think running a select query from the view is the worst thing in the world. Though I'm no expert... ;)
I had asked this question a while ago in regards to CodeIgniter... passing an Array to the view and looping through it seemed to be the favored response...
Using CodeIgniter is it bad practice to load a view in a loop
精彩评论