Blog

DIY tips: Propel does a great job for Views

2007-06-05 10:52:27 by Martynas Jusevičius

You often want your views (especially those which list items) to do sorting, filtering, paging and that kind of things. Using Propel, you can achieve that by calling a few simple methods, without a single line of SQL!

Here is how our View class for listing blog posts looks like:

class PostListView extends XSLTView
{
	function display(Request $request, Response $response)
	{
		$pageForm = new PageForm($request);
		
		$offset = 0;
		if ($pageForm->getOffset() != null) $offset = $pageForm->getOffset();
		$limit = 10;
		if ($pageForm->getLimit() != null) $limit = $pageForm->getLimit();
		$desc = true;
		if ($pageForm->getDesc() == "false") $desc = false;
		$orderBy = 1;

		$c = new Criteria();
		$c->add(PagePeer::TYPE, PagePeer::CLASSKEY_POSTPAGE);

		$postCount = PagePeer::doCount($c);

		$c->setLimit($limit);
		$c->setOffset($offset);
		if ($desc)
		{
			$c->addDescendingOrderByColumn(PagePeer::DATETIME);
			$c->addDescendingOrderByColumn(PagePeer::TITLE);
		}
		else
		{
			$c->addAscendingOrderByColumn(PagePeer::DATETIME);
			$c->addAscendingOrderByColumn(PagePeer::TITLE);
		}

		$posts = PagePeer::doSelectJoinAll($c);

		$this->proc->setParameter("", "total-item-count", $postCount);
		$this->proc->setParameter("", "offset", $offset);
		$this->proc->setParameter("", "limit", $limit);
		$this->proc->setParameter("", "desc", $desc);

		$this->resolver->setArgument("posts", XMLSerializer::serialize($posts));

		$this->template->load(ROOT_DIR."view/views/postList/PostList.xsl");

		parent::display($request, $response);
	}

}

The parameters are used for paging. offset specifies the number of posts to skip (i. e. the post number where the result should start at), limit specifies the number of posts in the result (on one page), and desc specifies whether it should be sorted in the descending order or not.

We just retrieve request parameters using a Form, pass them to Propel to do the sorting/filtering stuff (using Criteria and PagePeer classes), and then pass them to XSLT — that's it, the job is done.

Digg Digg this! del.icio.us del.icio.us!

New comment






No HTML allowed.