Symfony 2 : A “parent” controller for performance – part 1

I’ve been using Symfony 2 (SF2) for a while (since 2.0 release in fact), especially with MongoDB.

Couple of things I have noticed:

  • Service “name” could change. If means, for example, that your ‘doctrine.blahbla.mongodb’ could become one day ‘doctrine.blah.mongo.db’. It happens between SF 2.1 and 2.6, meaning you have to rewrite access to “DocumentManager”
    (you know, the famous

    $dm = $this->get('doctrine.....mongodb')
  • Service retrieval is quite slow and could be speed up through “caching” and so on…
  • Translate some strings from controller piss me off because of the “$this->get(‘translator’)->trans(…) which is so long.

So, all my controllers extends from a “Parent One” instead of usual Symfony Controller, which caches services and provides basic functions to make the code more readable.

Here is it (couple of functions)

class AAController extends Controller {

  /**
   * Retrieve MongoDB Document Manager
   */
  public function getDM() {
    if (!isset($this->_dm)) $this->_dm = $this->get('doctrine....mongodb');
    return $this->_dm;
  }

  /**
   * Retrieve translator service
   */
   public void getTranslator() {
    if (!isset($this->_trans)) $this->_trans = $this->get('translator');
    return $this->_trans;
   }

   /**
    * Translate a string
    */
   public function trans($msg) {
     return $this->getTranslator()->trans($msg);
   }

}

Juste to give you an idea of performance improvements:

  1. Retrieving a service with “caching” is at least 10x times faster
  2. If service name changes, it is quite easy to upgrade.

And honestly, I wonder why SF framework is not caching access to service natively – Part 1