Skip to content

Instantly share code, notes, and snippets.

@mmiliaus
Last active December 19, 2015 01:29
Show Gist options
  • Save mmiliaus/5876679 to your computer and use it in GitHub Desktop.
Save mmiliaus/5876679 to your computer and use it in GitHub Desktop.

Controller

Request

  • get request parameter: $request->getParameter('id')

Redirect

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

Plain Text response

  public function indexSuccess($request) {
        $this->getResponse()->setHttpHeader('Content-Type',' text/plain');
        $this->getResponse()->setContent("OK");
        return sfView::NONE;
  }

Filters

Custom Filters

Custom filters can be added to lib/filters directory.

An example filter definitions:

class sfSecureFilter extends sfFilter
{
  public function execute($filterChain)
  {
    $context = $this->getContext();
    $request = $context->getRequest();
 
    if (!$request->isSecure())
    {
      $secure_url = str_replace('http', 'https', $request->getUri());
 
      return $context->getController()->redirect($secure_url);
      // We don't continue the filter chain
    }
    else
    {
      // The request is already secure, so we can continue
      $filterChain->execute();
    }
  }
}
class sfGoogleAnalyticsFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // Nothing to do before the action
    $filterChain->execute();
 
    // Decorate the response with the tracker code
    $googleCode = '
<script src="http://www.google-analytics.com/urchin.js"  type="text/javascript">
</script>
<script type="text/javascript">
  _uacct="UA-'.$this->getParameter('google_id').'";urchinTracker();
</script>';
    $response = $this->getContext()->getResponse();
    $response->setContent(str_ireplace('</body>', $googleCode.'</body>',$response->getContent()));
   }
}

Forward or Redirect

As an action can forward or redirect to another action and consequently relaunch the full chain of filters, you might want to restrict the execution of your own filters to the first action call of the request. The isFirstCall() method of the sfFilter class returns a Boolean for this purpose. This call only makes sense before the action execution.

Example:

class rememberFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // Execute this filter only once
    if ($this->isFirstCall())
    {
      // Filters don't have direct access to the request and user objects.
      // You will need to use the context object to get them
      $request = $this->getContext()->getRequest();
      $user    = $this->getContext()->getUser();
 
      if ($request->getCookie('MyWebSite'))
      {
        // sign in
        $user->setAuthenticated(true);
      }
    }
 
    // Execute next filter
    $filterChain->execute();
  }
}

Forwarding:

return $this->getContext()->getController()->forward('mymodule', 'myAction');`

Enabling filter

Custom filters can be enabled in config/filters.yml.

Example config/filters.yml:

rendering: ~
security:  ~

remember:                 # Filters need a unique name
  class: rememberFilter
  param:
    cookie_name: MyWebSite
    condition:   %APP_ENABLE_REMEMBER_ME%

cache:     ~
execution: ~

Getting parameters from filters.yml configuration:

class rememberFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // ...
 
    if ($request->getCookie($this->getParameter('cookie_name')))
    {
      // ...
    }
 
    // ...
  }
}

View

  • Custom date format: <?php echo $job->getDateTimeObject('created_at')->format('m/d/Y') ?>

Form

<?php echo form_tag_for($form, '@job') ?>

Methods:

  • hasGlobalErrors()
  • getGlobalErrors()
  • renderGlobalErrors()

Widget

Methods:

  • renderRow() Renders the field row
  • render() Renders the field widget
  • renderLabel() Renders the field label
  • renderError() Renders the field error messages if any
  • renderHelp() Renders the field help message

Example:

      <tr>
        <th><?php echo $form['category_id']->renderLabel() ?></th>
        <td>
          <?php echo $form['category_id']->renderError() ?>
          <?php echo $form['category_id'] ?>
        </td>
      </tr>

Routes

job_show_user:
  url:   /job/:company/:location/:id/:position
  class: sfRequestRoute
  param: { module: job, action: show }
  requirements:
    id: \d+
    sf_method: [get]

Object Route

  • config/routing.yml:

    job_show_user:
      url:     /job/:company/:location/:id/:position
      class:   sfDoctrineRoute
      options: { model: JobeetJob, type: object }
      param:   { module: job, action: show }
      requirements:
        id: \d+
        sf_method: [get]
  • ../indexSuccess.php:

    <?php echo link_to($jobeet_job->getPosition(), 'job_show_user', $jobeet_job) ?>

Collection Routes

```yaml
job:
  class:   sfDoctrineRouteCollection
  options: { model: JobeetJob }
```

**Using different field for identification than id:

job:
  class:        sfDoctrineRouteCollection
  options:      { model: JobeetJob, column: token }
  requirements: { token: \w+ }

More

Configuration

get parameter sfConfig::get('app_active_days')

Generators

  • generate admin for model: ./symfony doctrine:generate-admin backend JobeetCategory --module=category

Misc

  1. Get current application name: $this->getContext()->getConfiguration()->getApplication();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment