Wednesday, May 19, 2010

Symfony Tips

1. Add Timer (symfony 1.0)

/**** init timer *****/
$timer = sfTimerManager::getTimer('myTimer');
/**********/


/**** display timer *****/
$timer->addTime();
$elapsedTime = $timer->getElapsedTime();
echo $elapsedTime;
die();
/**********/


2. Unit Test (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/08
Create test.php file under ProjectName/test/unit/test

// test/unit/JobeetTest.php
require_once dirname(__FILE__).'/../bootstrap/unit.php';

$t = new lime_test(1);
$t->pass('This test always passes.');


To launch the test
$ php test/unit/test.php

Sample

require_once dirname(__FILE__).'/../bootstrap/unit.php';
$t = new lime_test(6); // display 1..6

$t->comment('::slugify()'); // display #::slugify()
$t->is(Jobeet::slugify('Sensio'), 'sensio', '::slugify() converts all characters to lower case'); // display ok 1 - ::slugify() converts all ...


3. User Flash (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13
A flash is an ephemeral message stored in the user session that will be automatically deleted after the very next request. It is very useful when you need to display a message to the user after a redirect.

setFlash(): The first argument is the identifier of the flash and the second one is the message to display. You can define whatever flashes you want, but notice and error are two of the more common ones.
// apps/frontend/modules/job/actions/actions.class.php
public function executeExtend(sfWebRequest $request)
{
    $request->checkCSRFProtection();

    $job = $this->getRoute()->getObject();
    $this->forward404Unless($job->extend());

    $this->getUser()->setFlash('notice', sprintf('Your job validity has been extended until %s.', $job->getDateTimeObject('expires_at')->format('m/d/Y')));

    $this->redirect($this->generateUrl('job_show_user', $job));
}

Include the flash message in the templates
// apps/frontend/templates/layout.php
<?php if ($sf_user->hasFlash('notice')): ?>
  <div class="flash_notice"><?php echo $sf_user->getFlash('notice') ?></div>
<?php endif ?>
 
<?php if ($sf_user->hasFlash('error')): ?>
  <div class="flash_error"><?php echo $sf_user->getFlash('error') ?></div>
<?php endif ?>


4. User Attribute (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13
getAttribute(), setAttribute()

// apps/frontend/modules/job/actions/actions.class.php
class jobActions extends sfActions
{
    public function executeShow(sfWebRequest $request)
    {
    $this->job = $this->getRoute()->getObject();

    // fetch jobs already stored in the job history
    $jobs = $this->getUser()->getAttribute('job_history', array());

    // add the current job at the beginning of the array
    array_unshift($jobs, $this->job->getId());

    // store the new job history back into the session
    $this->getUser()->setAttribute('job_history', $jobs);
    }
}

myUser class
The myUser class overrides the default symfony base sfUser class with application specific behaviors

// apps/frontend/modules/job/actions/actions.class.php
class jobActions extends sfActions
{
    public function executeShow(sfWebRequest $request)
    {
    $this->job = $this->getRoute()->getObject();

    $this->getUser()->addJobToHistory($this->job);
    }
}
// apps/frontend/lib/myUser.class.php
class myUser extends sfBasicSecurityUser
{
    public function addJobToHistory(JobeetJob $job)
    {
    $ids = $this->getAttribute('job_history', array());

    if (!in_array($job->getId(), $ids))
    {
        array_unshift($ids, $job->getId());
        $this->setAttribute('job_history', array_slice($ids, 0, 3));
    }
    }
}

remove attribute
User's attributes are managed by an object of class sfParameterHolder. The getAttribute() and setAttribute() methods are proxy methods for getParameterHolder()->get() and getParameterHolder()->set().

// apps/frontend/lib/myUser.class.php
class myUser extends sfBasicSecurityUser
{
    public function resetJobHistory()
    {
        $this->getAttributeHolder()->remove('job_history');
    }
}



5. i18n and l10n (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/19
User Culture
The language French is ‘fr’, English is ‘en’; the country Canada is ‘CA’, United States is ‘US’; the culture for a user speaking French from Canada is ‘fr_CA’
setCulture()and getCulture()

// in an action
$this->getUser()->setCulture('fr_BE');
echo $this->getUser()->getCulture();

The preferred user culture can be configured in the settings.yml configuration file

#apps/frontend/config/settings.yml
all:
    .settings:
       default_culture: en_CA

Internationalization
set i18n setting to true in settings.yml

# apps/frontend/config/settings.yml
all:
   .settings:
       charset: utf-8
       i18n: true

The I18N helper group is not loaded by default, you need to either manually add itin each template with use_helper(‘I18N’) or load it globally by adding to the standard_helpers setting

# apps/frontend/config/settings.yml
all:
   .settings:
      standard_helpers: [Partial, Cache, I18N]

Sample template of how to use the __() helper

    // apps/frontend/templates/layout.php

      <a href=""><?php echo __('About Jobeet') ?></a>

      <?php echo link_to(__('Full feed'), 'job', array('sf_format' => 'atom')) ?>

    Create catalogue using i18n:extract

    $ php symfony i18n:extract frontend fr --auto-save

    Each translation is managed by a trans-unit tag which has a unique id attribute. A lot of tools exist to ease the translation process. (check out Open Language Tools https://open-language-tools.dev.java.net/)

    <!-- apps/frontend/i18n/fr/messages.xml -->

    <xliff version="1.0">
      <file source-language="EN" target-language="fr" datatype="plaintext"
          original="messages" date="2008-12-14T12:11:22Z"
          product-name="messages">
        <header/>
        <body>
          <trans-unit id="1">
            <source>About Jobeet</source>
            <target>A propos de Jobeet</target>
          </trans-unit>
          <trans-unit id="2">
            <source>Feed</source>
            <target>Fil RSS</target>
          </trans-unit>
        </body>
      </file>
    </xliff>

    How to use format_date
    sfDateFormat::getPattern()
    http://fellipeeduardo.com/blog/symfony-helper-format_date-how-to-use/en/

    6. autoload.yml (symfony 1.4)
    http://www.symfony-project.org/reference/1_4/en/14-Other-Configuration-Files
    The autoload.yml configuration determines which directories need to be autoloaded by symfony

    7. Authentication (symfony 1.4)
    entire application require the user to be authenticated

    # apps/backend/config/security.yml
    default:
       is_secure: true

    when an un-authenticated user tries to access a secured action, symfony forwards the request to the login action

    # apps/backend/config/setting.yml
    all:

      .actions:
         login_module: default
         login_action: login


    By default, the myUser class extends sfBasicSecurityUser, and not sfUser. sfBasicSecurityUser provides additional methods to manage user authentication and authorization.

    To manage user authentication, use the isAuthenticated() and setAuthenticated() methods:

    if (!$this->getUser()->isAuthenticated())
    {
        $this->getUser()->setAuthenticated(true);
    }


    8. Basic File Structure (1.2)
    http://www.symfony-project.org/book/1_2/19-Mastering-Symfony-s-Configuration-Files

    sf_root_dir # myproject/
    sf_apps_dir # apps/
    sf_app_dir # frontend/
    sf_app_config_dir # config/
    sf_app_i18n_dir # i18n/
    sf_app_lib_dir # lib/
    sf_app_module_dir # modules/
    sf_app_template_dir # templates/
    sf_cache_dir # cache/
    sf_app_base_cache_dir # frontend/
    sf_app_cache_dir # prod/
    sf_template_cache_dir # templates/
    sf_i18n_cache_dir # i18n/
    sf_config_cache_dir # config/
    sf_test_cache_dir # test/
    sf_module_cache_dir # modules/
    sf_config_dir # config/
    sf_data_dir # data/
    sf_doc_dir # doc/
    sf_lib_dir # lib/
    sf_log_dir # log/
    sf_test_dir # test/
    sf_plugins_dir # plugins/
    sf_web_dir # web/
    sf_upload_dir # uploads/


    9. Use Helper in Action
    http://snippets.symfony-project.org/snippet/69
    In PrjectConfiguration file

    # ProjectName/config/ProjectConfiguration.class.php
    include_once('/opt/symfony/symfony14/lib/helper/DateHelper.php');

    In Action
    format_date(time(), 'D', 'fr');

    Format
    http://trac.symfony-project.org/wiki/formatDateHowTo

    No comments:

    Post a Comment