Updates from May, 2011 Toggle Comment Threads | Keyboard Shortcuts

  • Pablo 9:57 PM on 24 May 2011 Permalink | Reply  

    Symfony2 BETA2 !!! 

    Today i found out of the release of the BETA2 of Symfony2! http://symfony.com/download

    I was in the middle of my site development with BETA1, but i had to be up to date! i thought it was going to be hard to make the upgrade but in a matter or MINUTES, mabe 5 minutes, i was all ready and running from where i left it.

    If you think that every change that the Symfony people does is only for the better and to make our lifes easyer, you start being less afraid of new releases. I knew this was going to be only for the best.

    Ok. That’s all! I have to get back to my site! Symfony ROCKS!!!!

    • Rich 3:03 PM on 10 June 2011 Permalink | Reply

      And can you believe it’s already Beta 4? Thanks for the blog man. We need more SF2 resources!

    • phicheth 4:46 PM on 9 September 2011 Permalink | Reply

      doSymfony2.0.1-20110909 Ready Edition is a full repo package include all vendors including in symfony 2.0.1 standard edition. Ready Edition – No git request. all you need already include in pack. Accept share hosting, VPS or your own server.

      Detail of work:

      remove ‘/web/’ folder with edit vendors file. can run on share hosting without any issue from remove ‘/web/’ folder.
      update all vendors via git to build a package. you can use git update symfony with ‘ php bin/vendors install ‘ anytime you wanted. to update to new version you must replace ‘deps’ and ‘deps.lock’ files before update new version of Symfony2
      all feature, API and docs please follow from http://www.symfony.com

      Download : http://code.google.com/p/dohew-opensource/

      This is Symfony2 package include all vendors needed ***

      This package update by Phicheth Kijtaow @doHew Media!

  • Pablo 11:28 AM on 19 May 2011 Permalink | Reply  

    Symfony2: HTTP Cache [part3] – ETags 

    ETags allows you to set a cached content invalid when it has non-matching ETags (the etags form the cached content and the new etag generated by the server)

    public function indexAction()
        $response = new Response();
        $response->setETag(md5( ...whatever you want...));
         if( $response->isNotModified($this->get('request')) )
             return $response; //THis will automaticall return aNULL content with a 304 header (not modified)
             //Generate the contents and responde. THis response will have the ETage generated above.
             return  $this->renderView('MyBundle:Main:index.html.twig', array(), $response);

    So the Etags in combination with the Max Age header can allow you to cache data but let you make last minute changed and still let the server responde the correct response.

    I would say that a cool Etag value could be MD5( the name of the resource+the revision number (if you use svn) )

    read more

  • Pablo 5:46 PM on 18 May 2011 Permalink | Reply  

    Symfony2: Translations 

    To get the Translator you must use the dependecy injector inside the controller, basically you do this:


    You must have it enabled on the config:

        translator: { fallback: en }

    Now you put all your translations dictionaries on the path:

    • YourApp/YourBundle/Resources/translations
    • Or… if you want to override definitions from other bundles, you put them on app/Resources/translations
    There will be one translation file per language, and it can be in PHP, YML or XLIFF format. The naming convention is: DOMAIN.LOCALE.FORMAT (example:  messages.es.xliff  — Messages in spanish using xliff format )
    Example (messages.es.xliff):
    <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
        <file source-language="en" datatype="plaintext" original="file.ext">
                <trans-unit id="1">
                    <target><![CDATA[ <strong>Symfony2</strong> esta bueno. ]]></target>

    And on the controller you call:

            $t = $this->get('translator')->trans('symfony.rocks') ;
            return new Response($t);

    You will get the message according to the current Locale language (in this case “es”)

    Another cool feature from Symfony is the possibility to set the language in the URL of each page and automaticaly set the correct Locale on the session, to do that you use the _locale feature in the routes:

         * @extra:Route("/{_locale}/YourRoute", name="_testing", requirements={"_locale"="en|fr|es"})

    In the above example, depending on the value of _locale symfony will automatically set the correct language, so you dont have to use setLocale on the Translator!

    Read more from the official documentation.

  • Pablo 5:02 PM on 18 May 2011 Permalink | Reply  

    Symfony2: HTTP Cache [part 2] -> Edge Side Includes 

    ESI allows you to cache PARTS of your application on the same Response, so for example, you could have a website with a static home page which can be cached for 24 hours while it could contain a small part of it which shows mabe the latest forum posts. You would want to generate the home one time, but get the recent forum posts each 5 minutes, that´s when you know you need to use ESI.

    To enable it:

        esi: { enabled: true }

    To use it, you render your home as you would normally do, but on the template, in the part of your html where you want to put the latest forum blocks (as an example) you put this (using Twig):

    {% render 'SomeCrazyBundle:Forum:latest' with {}, {'standalone': true} %}

    The standalone=true will tell Symfony2 to use ESI. The action latestAction from the ForumController will now be able to return the latest forum posts setting the MaxAge to whatever it needs (15 for example)

    If you test this refreshing the page many times, you will see how the block changes but the home dont (set 3 seconds and 10 seconds for the home for fast testing)

  • Pablo 1:24 PM on 18 May 2011 Permalink | Reply  

    Symfony2: HTTP Cache [part 1] 

    Ok, so Symfony has a cache layer which you can use to cache your responses. At first i was confused about why should i use this cache when i already could set Control-Cache headers on the responses. Then i did this little experiment to see what was the deal:

    Open 2 diferent browsers and call a test page with it´s controller set like this:

    class DefaultController extends Controller
         * @extra:Route("/", name="_base")
        public function indexAction()
            $response = new Response();
            $response->setMaxAge(10); //< 10 seconds! you can test this refreshing the page.
           return $this->render('SomeBundle:Default:index.html.twig', array('rand'=>rand()), $response); //this twig renders a random number to test that the response is actually cached.

    If you DONT use the AppCache, when you open the page in the 2 diferent browsers, you will see 2 diferent responses. Then the cache will be handled by the browser.

    But if you DO use the AppCache, the 2 browsers will show the SAME response, the cache will still be handled by the browser, but using the initial cached data provided by the AppCache layer:

    # app.php
    //require_once __DIR__.'/../app/bootstrap.php.cache';
    //require_once __DIR__.'/../app/AppKernel.php';
    require_once __DIR__.'/../app/bootstrap_cache.php.cache';
    require_once __DIR__.'/../app/AppCache.php';
    use Symfony\Component\HttpFoundation\Request;
    $kernel = new AppCache(new AppKernel('prod', true));
    //$kernel = new AppKernel('prod', false);

    So in the above example, 100 users could ask for the same url ( inside the MaxAge timeframe of the response ) and all would get the SAME response, so the response would be generated only once. If you didnt used the cache layer, your app would have to generate 100 responses before using the cache from each user´s computer.

    Keep reading more: HTTP Cache tutorial.

  • Pablo 12:41 PM on 17 May 2011 Permalink | Reply  

    Symfony2: Custom Validation Constraint 

    To add a custom validator constraint, add this to your config.yml (as an example…):

          enabled: true
                  test: Book\Store4Bundle\validator\

    The namespaces is a list of the namespaces to your custom constraints, for example now when you do @test:Etc symfony will search for a class named Etc on the namespace assosiated with test, which is: book/store4bundle/validator. So you do this one time only and then you create your classes in the correct namespace and you´re good to go! Nelow you can see an object that uses the custom validator on one of it´s fields.

    class Test
         * @test:AlwaysFail()
        public $name;

    AllwaysFail and Validator class:

    // AlwaysFail.php
    namespace Book\Store4Bundle\validator;
    use Symfony\Component\Validator\Constraint;
    class AlwaysFail extends Constraint
          public $message = 'This value is not a valid TEST';
        public function getTargets ()
            return Constraint::PROPERTY_CONSTRAINT;

    And the validator class:

    // AlwaysFailValidator.php   <-- Symfony automatically search for this class! CLASS+Validator.php
    namespace Book\Store4Bundle\validator;
    use Symfony\Component\Validator\ConstraintValidator;
    use Symfony\Component\Validator\Constraint;
    class AlwaysFailValidator extends ConstraintValidator
        public function isValid ( $value, Constraint $constraint )
            $this->setMessage("Nope, always fail!");
            return false;

    The above example will search for a class named AlwaysFail in the Book\Store4Bundle\validator namespace.

    The class must extends Constraint, and it must exists another class named %CLASSNAME%Validator which must extends ConstraintValidator. In the above example it would be AlwaysFailValidator.

    It was actually hard to figure this out, because the documentation is not very clear, i had to search for “assert” on the symfony files, and i got to line 488 of the file FrameworkExtension.php (from the zip BETA1 Symfony2), then i knew that the new namespaces were declared in the config and also that the class in charge of loading annotations is called AnnotationLoader.php…

    You can see more information on all the constraint that comes with Symfony investigating this namespace: Symfony\Component\Validator\Constraints;

    Now you can read the official documentation understanding how actually making this work!

    • bux 3:00 PM on 1 December 2011 Permalink | Reply

      outdated article ?

      • bux 3:00 PM on 1 December 2011 Permalink | Reply

        <> => InvalidConfigurationException: Unrecognized options “enable, annotations” under “framework.validation”

      • Pablo Bandin 9:28 PM on 1 December 2011 Permalink | Reply

        I wrote that article when Symfony was on release candidate versions, since then it changed a lot. Now it’s finally on a stable version.
        ATM i’m not into Symfony anymore, im doing other projects, but i still like Symfony2 a lot.

        But look into their documentation, they had updated it a lot and now is much better. CHeck out their Cookbook.

  • Pablo 7:48 AM on 12 May 2011 Permalink | Reply  

    Symfony2 ExtraBundle ref 


  • Pablo 8:45 AM on 11 May 2011 Permalink | Reply  

    Symfony2 & Sessions 

    To get the session in Symfony2 you call the “session” service (in this example, from inside a controller instance):

    $session  = $this->get("session");

    This will give you a Session object which you can then use to store session data. All the setXXX methods start the session if is not already, so you dont need to call $session->start() most of the time. This class uses inernally a NativeSessionStorage which wraps the classic $_SESSION object. There are other SessionStoreage objects, idk yet how to use them.

    • Paloma 7:46 AM on 31 January 2012 Permalink | Reply

      Thank you, very simple but i couldn’t find it in symfony’s 2 book

    • Robert 7:02 AM on 21 April 2012 Permalink | Reply

      Thank you!

    • Medy 8:42 AM on 24 May 2012 Permalink | Reply

      hey , i’m using FOSUserBundle to log my users, and this bundle create a session after the login ,
      i want to get the data of my user in the Controller, then print it in the twig.

      well if you can explain this to me in general state, cause i’m new to symfony ! thanks for helping

      • Pablo Bandin 2:17 PM on 30 May 2012 Permalink | Reply

        Sorry, i’m not into Symfony anymore, so i had lost the groove with it, wouldn’t be able to help you.

      • Lumbendil 5:04 AM on 8 June 2012 Permalink | Reply

        If you only need the user information in twig, you can access it doing the following:

        {{ app.user }}

        so, if you want the username, you would to {{ app.user.username }}

        To get it in the controller, you need to do the following:

        $user = $this->get(‘security.context’)->getToken()->getUser();

        Hope it helps

        • TomBombadil 12:52 AM on 8 August 2012 Permalink

          Do you know if that token/user method uses standard PHP session objects, or is it maintaining them differently? I was hoping to do cookie-based security tokens (to work in load-balanced environments) and it would be nice if the FOS user bundle offered that

        • Pablo Bandin 3:30 PM on 8 August 2012 Permalink

          Symfony abstracts the session handling, it can handle regular sessions (a server side cookie), database sessions (storing in a database) etc… but you use one shared interface, regardless of the underlying concrete storage method used. You can even create your own storage handler.

          Check out the sourcecode to see in more details.

  • Pablo 11:49 PM on 10 May 2011 Permalink | Reply  

    Symfony2: Access Control Lists (ACLs) 

    Well this thing is being a little bitch to understand… anyway, this is what i get so far:

    First you need to tell the ACL system which connection will use, because it uses a database to create a bunch of tables that needs to create this relations between objects and entities.

    # app/config/security.yml security: acl: connection: default
    Then, to let the system create the required tables for this thing to work, you have to execute this command:
    php app/console init:acl
    Now you have 5 new tables in your database, which will relate each object with their respective entities and relations.
    When you use ACLs you basically create Access Lists for ObjectIdentityInterfaces, each of this object will have a list of the UserSecurityIdentities that can have some type of access to this entities. For example, one User might be able to delete an entity while other might just be able to read this entity ( view it ), so this lists hold the permissions that each User has over them.
    To create an ACL for an object (we do this just one time if non exits) you do this:
            // creating the ACL
            $aclProvider = $this->container->get('security.acl.provider');
            $objectIdentity = ObjectIdentity::fromDomainObject($comment);
            $acl = $aclProvider->createAcl($objectIdentity);
    We first took our object and created an ObjectEntity from it, then created the ACL for this entity. Or if its already created you do:
    $acl = $aclProvider->findAcl($objectIdentity);
    Now, at this point we have an ACL, to write something in it, you will need to get the user in which you want to assign permissions, generally this is the currently logged user:
    // retrieving the security identity of the currently logged-in user
            $securityContext = $this->container->get('security.context');
            $user = $securityContext->getToken()->;getUser();
            $securityIdentity = UserSecurityIdentity::fromAccount($user);
    Now we have our user ( UserInterface object ) turned into a SecurityEntity, we can now start doing the thing for which this ACL is made for:
    $acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
    Here we are saying to the ACL , if i understood correctly, that for this specific object, the current user will have OWNER access over it. This is just for this object.
    So in this case, the control entity will rule for just that object. I didnt test it, but according to the docs, you can also set control access for ALL instances of the object, of for just a field of the object, and other options.  Check out the ACL class for all the things you can do on an ACL.
    Ok, now that we know how to get an ACL, to check for the permissions of an user we just do:
    $acl->isGranted( array(MaskBuilder::MASK_OWNER), array( $securityIdentity) ); //has this user OWNER rights over this object??

    Someone correct me if i’m mistaken, im just learning this stuff myself.

    • sebwebdev 7:45 AM on 30 June 2011 Permalink | Reply

      Note that you can also use the security context service from within the controller to check if perms were granted, e.g.:
      if ( ! $this->get(‘security.context’)->isGranted(‘EDIT’, $entity)) {
      throw new AccessDeniedException();

    • Dominik 9:18 AM on 8 September 2011 Permalink | Reply

      Is this not the same article found in the symfony 2 documentation?

    • jk 6:28 AM on 7 October 2011 Permalink | Reply

      Dominik I beleive it’s the same only here you can comment and discuss it. It would be a big plus if you could do it on the official docs too. Django book has this option.

  • Pablo 11:21 PM on 8 May 2011 Permalink | Reply  

    Symfony2 & Doctrine2: ManyToMany Association 

    Quick ref: Let’s say you have 2 Entities, one is called Author and the other Book, one author can have many books, and one book can have many Authors, you will need a ManyToMany association. So in your Author Entity class you put this annotation:

    –The Annotation:

    #Inside the Author.php class
         * @orm:ManyToMany(targetEntity=&quot;Book&quot;, cascade={&quot;persist&quot;})
        private $book; //this will contain a Collection of many Book objects

    — Database Creation & Stub Methods auto-generation

    That’s it, now, according to the default behaviour, after executing this (which creates the tables):

    php app/console doctrine:schema:create

    Your database will now have (in this example) 3 tables, one named author, book and one called author_book. This last table is the one that will store the relation between author and book. Now you need to auto-generate the stub methods:

    php app/console doctrine:generate:entities YourAppYourBundle

    After that, you will have a method called  addBook and getBook, and if you look at the source code, you will see that the book property is a collection of Book entities. This will also rename your original classes and prefix them with a ~ sign. You can delete this fiels after creation of the final classes, if not, you will get a “cant redeclare class” bullshit when calling generate entities again.


    Now, if you can (this code you can test it inside a controller’s action):

           $em = $this->get("doctrine.orm.entity_manager");
        	$book1= new Book();
        	$book1->setName("The Naked Sun");
        	$book2 = new Book();
        	$book2->setName("The Robots of Dawn");
        	$author = new Author();
        	$author->setName("Isaac Asimov");
    // Saving the author ( this will also save the Books, because of the "cascade={'persist'}" attribute on the annotation)
        	$em->persist(author); //<- Note how we only save the author! Doctrine then makes all the dirty work for us!

    Now, when retrieving the author a property called ->getBook() will give you a Collection of Book objects:

            $issac_asimov = $em->find('YourAppYourBundle:User', 1);
            $issac_asimov->getBook(); //this will have all the books from this author.

    PS: the $em->find method internally calls the default EntityRepository for the entity if no custom was defined on the annotations, which in turn returns an User entity based on the id: 1

    • pascal 9:43 AM on 21 June 2011 Permalink | Reply

      Thanks for the simple example.. I find doctrine2 doc missing examples/tutorials…

    • Tobias 12:58 PM on 7 July 2011 Permalink | Reply

      Great post. I really like the magic with the php app/console doctrine:generate:entities YourAppYourBundle command

    • manu 10:28 AM on 13 July 2011 Permalink | Reply

      So… the link table is generated by doctrine ? What if I want to add fields in it ?

    • manu 10:43 AM on 13 July 2011 Permalink | Reply

      Oh I see. “Foreign keys as identifiers are currently in master and will be included in Doctrine 2.1”

    • Luke 4:52 AM on 11 October 2011 Permalink | Reply

      Does this generate an additional association class? I also need to add an additional attribute to my join table

    • Cethy 10:23 AM on 28 October 2011 Permalink | Reply

      @Luke & manu : You need to make a one2many2one (1:*:1) relation. As in doctrine1, doctrine2 does not support this kind of stuff yet.

    • Matteo 6:56 PM on 18 November 2011 Permalink | Reply

      Two times I have needed about Symfony2, and two times I have found solution here. Great blog!

    • Permana Jayanta 11:46 PM on 8 January 2013 Permalink | Reply

      And where is the Book Entity? Sorry, I’m a little bit noob here

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc