Updates from August, 2011 Toggle Comment Threads | Keyboard Shortcuts

  • Pablo 11:44 AM on 23 August 2011 Permalink | Reply  

    Symfony2: Working with Assetic 

    Well, i finally took the time to read something about Assetic and let me tell you, it’s awesome. This is how it works:

        {% javascripts '@yourBundle/Resources/js/*' output='js/combined.js' %}
        <script src="{{ asset_url }}"></script>
        {% endjavascripts %}
    

    The code above ( used inside a Twigg template ) will pack all the javascripts inside Resources/js folder and put them all inside a single file called combined.js inside the web/js folder.

    While developing, that process will take a lot of time each time you refresh the page, that’s why you will want to call this command to make Assetic watch for changes every X time to generate a physical version of each file so the files can be served directly to the browser rather than being generated at runtime:

    php app/console assetic:dump --watch

    That will create a bunch of javascripts in the web/js folder, and everytime you change a file in your Resources/js it will be automatically updated in your web/js folder. So now page load times will be optimal.

    Also, on production, one javascript per javascript will be generated, this is fine because this way you can debug them easily. On Development, assetic will pack all the javascript on a single file (in the case of the example above).

    That’s for when you are developing. When deploying to production, you can delete all the files inside the web/js folder (generated by assetic on development) and run this command:

    php app/console assetic:dump --env=prod --no-debug

    That will generate the FINAL version of all the javascripts so that from now on, the browser will be served with physical javascripts and assetic will not be used anymore.

    Remember that everytime you make a change on the javascripts, you will have to run the command above to generate the final version and that will be the files you will have to upload to production.

    For more information go to http://symfony.com/doc/current/cookbook/assetic/asset_management.html

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

      you write to get asset from any folder not need to import from bundle.

      If you place js files in /web/assets/js/jquery.js you can use this by example.

      <script src="{{ asset('assets/js/jquery.js') }}" type="text/javascript"></script>

      —————————————————————————————————
      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 8:02 PM on 25 July 2011 Permalink | Reply  

    Symfony2: SecurityBundle 

    Outline of how it’s involved in Symfony2:

    1. AppKernel -> handle  is called ( look app.php )
    2. FrameworkBundle :: HttpKernel’s -> handle is called
    3. Component :: HttpKernel’s handle is called. Which then calls handleRaw
    4. The HttpKernel dispatches an kernel.request event.
    5. The event is captured by a Firewall previously set as a listener by the SecurityBundle’s security.xml
    6. The onKernelRequest method of this Firewall is called.
    7. The firewall loops trough all the AuthenticationListeners which where set here ( lines 213 to 225 ) as part of the Firewall and call it’s handle method.
    8. If a security violation is detected ( the authentication listeners will throw this exceptions ), a kernel.exception is detected by an ExceptionListener previosuly set in security_listeners.xml and registered in the Firewall at the time of the Request.
    So that’s an overview of how the SecurityBundle intercepts Requests and based on the reaction of the AuthenticationListeners will do nothing or throw an exception informing about the security violation.
    Step 4 is where the magic happens, as you can see, the Request is intercepted before reaching the actual controller. As described here:
    (The numbers in the image are NOT related with the numbers in this article, they are part of the image form the Symfony book)
     
    • nabil 9:40 AM on 18 August 2011 Permalink | Reply

      Hi, I need to insert in my augmented reality action script in flash builder a preloader for my 3D.DAE model, can u help me?

  • Pablo 3:38 PM on 25 July 2011 Permalink | Reply  

    Symfony2: Custom Authentication Provider 

    Source: How to create a custom Authentication Provider

    Regarding Security, in Symfony you have 2 providers. One is an Authentication provider and the other is an UserProvider.

    • An authentication provider is used to extract information from a request to be used  to identify the user.
    • An user provider is used to check if the user found by the authentication provider exists on our pool of users.
    So basically, the authentication provider finds information about an user on the Request and creates a TOKEN with that information. This token contains the credentials of the users. With that token, the security bundle tries to find a user using the available user Provider and tries to see if it finds one that has/match the currently found user Token. If nothing is found, an error is thrown telling so.
    Easy to understand example ( AP = Authentication provider. UP = User Provider ):
    AP:  -Hey UP, i think i found an user on the request, take a look at this token-
    UP:  -let me see… Mmhh.. yeah, i found one, your token is valid!-
    AP: -Ok, thanks. Hey Symfony Security layer, this token is valid!-
    Overview:
     
  • 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 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:

    $this->get('translator')
    

    You must have it enabled on the config:

    framework:
        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">
            <body>
                <trans-unit id="1">
                    <source>symfony.rocks</source>
                    <target><![CDATA[ <strong>Symfony2</strong> esta bueno. ]]></target>
                </trans-unit>
            </body>
        </file>
    </xliff>
    

    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:

    framework:
        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.
             $response->setPublic();
    
           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:

    <?php
    # 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);
    //$kernel->loadClassCache();
    $kernel->handle(Request::createFromGlobals())->send();
    

    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…):

    framework:
        validation:
          enabled: true
          annotations:
              namespaces:
                  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:

    <?php
    // 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:

    <?php
    // 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 

    http://bundles.symfony-reloaded.org/frameworkextrabundle/

     
  • 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.

c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel