Kohana v3

Reuse of View – Kohana v3

The title may be a little inappropriate but what I was trying to say is loading several output from a single view but with different content. I did it wrong before but managed to optimized and reuse the view instead using bind() method.

I have a page called post that contains a single post/mini-blog – just the post. No widgets, etc. And I display 20 posts on my homepage using the view post. I have the data and what I did before was to create 20 post view instances and render them like this:

// feeds / entries
if (isset($feeds) && !empty($feeds))
{
	foreach ($feeds as $feed)
	{
		// post/entry wrapper
		echo '<div class="entries">';
		
		// render single post
		$view = View::factory('post/post');
		$view->feed = $feed;
		echo $view;
		
		// post/entry clearer and close wrapper
		echo '<div class="clearer"></div>',
		'</div>';
	}
}

So it actually did the job by creating a view object, assigning the variables and render it. However, that was expensive and by looking at the Kohana Profiler, it includes 100+ files which is horrible. Usually I only got maximum of 83 for complicated pages.

Since I have a very hard time reading the Kohana v3 documentations, I need to look at the source code and look if there is something I could tweak to make it more efficient. Then I found the bind() method for Kohana_View. It binds the variable to the view so it can use the variable inside the view source code.

Finally I got the solution to create only one post view instance and bind dynamically bind the variables during the loop. The final version looks like this:

// feeds / entries
$view = View::factory('post/post');
if (isset($feeds) && !empty($feeds))
{
	foreach ($feeds as $feed)
	{
		// post/entry wrapper
		echo '<div class="entries">';
		
		// render single post
		$view->bind('feed', $feed);
		echo $view;
		
		// post/entry clearer and close wrapper
		echo '<div class="clearer"></div>',
		'</div>';
	}
}

Now, it only includes 82 or 83 files. And less memory usages. Anyway, the page is cached after it is rendered so performance is not that a big deal. But there are always room for improvement and because this is a personal project, I could not let things as bloated like these.

Leave a reply

Your email address will not be published. Required fields are marked *