Quality Coding

Month: September, 2011

Ruby 1.9.2 installation from source on Ubuntu

There are easier ways to install most up to date version of Ruby on your system , for e.g. RVM or rbenv but if you want to have full control over what are you installing because it will be your production system, then this post will show you how to do this.

To install Ruby from source you need to install some dependencies first
Continue reading “Ruby 1.9.2 installation from source on Ubuntu” »

Symfony2 pagination with controller as a service and data sorting

Symfony2 doesn’t provide any good pagination tools out of the box so to solve this quite important problem I have created my own solution.

I needed to be able to paginate data based on requested page and per_page parameters through GET and POST requests. Second important thing was to be able to sort displayed data by id, title, etc.

I could have created some Paginator class but I wanted to be able to tweak each part of the process as I see fit on a per controller basis and I wanted to be able to access necessary functions through very short function calls directly in a controller.

I decided to extend all my controllers with necessary helper functions which would be available across all of them whenever I need to paginate something.

First problem was extending the controllers. Symfony2 docs page http://symfony.com/doc/2.0/book/controller.html shows you how to create controllers in a vary common way, but what it doesn’t say is that in this way you won’t be able to extend all controllers without running into various problems with access to the service container and Doctrine2 EntityManager which is needed to work with your data.

The solution to above problems is to use controllers as a service which allows you to use class inheritance, interfaces etc. in any way you want.

Application setup

Lets assume the application is configured as follows:

  • bundle is located in src/Foo/DemoBundle
  • all controllers will extend ApplicationController class which extends Symfony\Bundle\FrameworkBundle\Controller\Controller
  • pagination template is located in here src/Foo/DemoBundle/Resources/views/Pagination/pagination.html.twig
  • all necessary twig macros will be stored in here src/Foo/DemoBundle/Resources/views/global_macros.html.twig

Continue reading “Symfony2 pagination with controller as a service and data sorting” »