Symfony2 Jobeet Day 14: Feeds

If you are looking for a job, you will probably want to be informed as soon as a new job is posted. Because it is not very convenient to check the website every other hour, we will add several job feeds here to keep our Jobeet users up-to-date.

Template Formats

Templates are a generic way to render content in any format. And while in most cases you’ll use templates to render HTML content, a template can just as easily generate JavaScript, CSS, XML or any other format.

For example, the same “resource” is often rendered in several different formats. To render an article index page in XML, simply include the format in the template name:

  • XML template name: AcmeArticleBundle:Article:index.xml.twig
  • XML template filename: index.xml.twig

In reality, this is nothing more than a naming convention and the template isn’t actually rendered differently based on its format.

In many cases, you may want to allow a single controller to render multiple different formats based on the “request format”. For that reason, a common pattern is to do the following:

public function indexAction()
{
    $format = $this->getRequest()->getRequestFormat();

    return $this->render('AcmeBlogBundle:Blog:index.'.$format.'.twig');
}

The getRequestFormat on the Request object defaults to html, but can return any other format based on the format requested by the user. The request format is most often managed by the routing, where a route can be configured so that /contact sets the request format to html while /contact.xml sets the format to xml.

To create links that include the format parameter, include a _format key in the parameter hash:

<a href="{{ path('article_show', {'id': 123, '_format': 'pdf'}) }}">
    PDF Version
</a>

Feeds

Latest Jobs Feed

Supporting different formats is as easy as creating different templates. To create an Atom feed for the latest jobs, create an index.atom.twig template:

<!-- src/Ens/JobeetBundle/Resources/views/Job/index.atom.twig -->
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Jobeet</title>
  <subtitle>Latest Jobs</subtitle>
  <link href="" rel="self"/>
  <link href=""/>
  <updated></updated>
  <author><name>Jobeet</name></author>
  <id>Unique Id</id>

  <entry>
    <title>Job title</title>
    <link href="" />
    <id>Unique id</id>
    <updated></updated>
    <summary>Job description</summary>
    <author><name>Company</name></author>
  </entry>
</feed>

In the Jobeet footer, update the link to the feed:

<!-- src/Ens/JobeetBundle/Resources/views/layout.html.twig -->
<!-- ... -->

<li><a href="{{ path('ens_job', {'_format': 'atom'}) }}">Full feed</a></li>

<!-- ... -->

Add a <link> tag in the head section of the layout to allow automatic discover by the browser of our feed:

<!-- src/Ens/JobeetBundle/Resources/views/layout.html.twig -->
<!-- ... -->

<link rel="alternate" type="application/atom+xml" title="Latest Jobs" href="{{ url('ens_job', {'_format': 'atom'}) }}" />

<!-- ... -->

In the JobController change the indexAction to render the template according to the _format:

// src/Ens/JobeetBundle/Controller/JobController.php
// ...

$format = $this->getRequest()->getRequestFormat();

return $this->render('EnsJobeetBundle:Job:index.'.$format.'.twig', array(
    'categories' => $categories
));

// ...

Replace the Atom template header with the following code:

<!-- src/Ens/JobeetBundle/Resources/views/Job/index.atom.twig -->
<!-- ... -->

  <title>Jobeet</title>
  <subtitle>Latest Jobs</subtitle>
  <link href="{{ url('ens_job', {'_format': 'atom'}) }}" rel="self"/>
  <link href="{{ url('EnsJobeetBundle_homepage') }}"/>
  <updated>{{ lastUpdated }}</updated>
  <author><name>Jobeet</name></author>
  <id>{{ feedId }}</id>

<!-- ... -->

From the JobController we have to send the lastUpdated and feedId to the template:

// src/Ens/JobeetBundle/Controller/JobController.php
// ...

return $this->render('EnsJobeetBundle:Job:index.'.$format.'.twig', array(
    'categories' => $categories,
    'lastUpdated' => $em->getRepository('EnsJobeetBundle:Job')->getLatestPost()->getCreatedAt()->format(DATE_ATOM),
    'feedId' => sha1($this->get('router')->generate('ens_job', array('_format'=> 'atom'), true)),
));

// ...

To get the date of the latest post, we have to create the getLatestPost() method in the JobRepository:

// src/Ens/JobeetBundle/Repository/JobRepository.php
// ...

public function getLatestPost()
{
    $query = $this->createQueryBuilder('j')
        ->where('j.expires_at > :date')
        ->setParameter('date', date('Y-m-d H:i:s', time()))
        ->andWhere('j.is_activated = :activated')
        ->setParameter('activated', 1)
        ->orderBy('j.expires_at', 'DESC')
        ->setMaxResults(1)
        ->getQuery();

    try {
        $job = $query->getSingleResult();
    } catch (\Doctrine\Orm\NoResultException $e) {
        $job = null;
    }

    return $job;
}

// ...

The feed entries can be generated with the following code:

<!-- src/Ens/JobeetBundle/Resources/views/Job/index.atom.twig -->
<!-- ... -->

{% for category in categories %}
  {% for entity in category.activejobs %}
    <entry>
      <title>{{ entity.position }} ({{ entity.location }})</title>
      <link href="{{ url('ens_job_show', { 'id': entity.id, 'company': entity.companyslug, 'location': entity.locationslug, 'position': entity.positionslug }) }}" />
      <id>{{ entity.id }}</id>
      <updated>{{ entity.createdAt.format(constant('DATE_ATOM')) }}</updated>
      <summary type="xhtml">
        <div xmlns="http://www.w3.org/1999/xhtml">
          {% if entity.logo %}
            <div>
              <a href="{{ entity.url }}">
                <img src="http://{{ app.request.host }}/uploads/jobs/{{ entity.logo }}" alt="{{ entity.company }} logo" />
              </a>
            </div>
          {% endif %}
          <div>
            {{ entity.description|nl2br }}
          </div>
          <h4>How to apply?</h4>
          <p>{{ entity.howtoapply }}</p>
        </div>
      </summary>
      <author><name>{{ entity.company }}</name></author>
    </entry>
  {% endfor %}
{% endfor %}

<!-- ... -->

Latest Jobs in a Category Feed

One of the goals of Jobeet is to help people find more targeted jobs. So, we need to provide a feed for each category.

First, let’s update the links to category feeds in the templates:

<!-- src/Ens/JobeetBundle/Resources/views/Job/index.html.twig -->
<div class="feed">
  <a href="{{ path('EnsJobeetBundle_category', { 'slug': category.slug, '_format': 'atom' }) }}">Feed</a>
</div>

<!-- src/Ens/JobeetBundle/Resources/views/Category/show.html.twig -->
<div class="feed">
  <a href="{{ path('EnsJobeetBundle_category', { 'slug': category.slug, '_format': 'atom' }) }}">Feed</a>
</div>

Update the CategoryController showAction to render the corresponding template:

// src/Ens/JobeetBundle/Controller/CategoryController.php
// ...

$format = $this->getRequest()->getRequestFormat();

return $this->render('EnsJobeetBundle:Category:show.'.$format.'.twig', array(
    'category' => $category,
    'last_page' => $last_page,
    'previous_page' => $previous_page,
    'current_page' => $page,
    'next_page' => $next_page,
    'total_jobs' => $total_jobs,
    'feedId' => sha1($this->get('router')->generate('EnsJobeetBundle_category', array('slug' =>  $category->getSlug(), '_format' => 'atom'), true)),
));

// ...

Eventually, create the show.atom.twig template:

<!-- src/Ens/JobeetBundle/Resources/views/Category/show.atom.twig -->
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Jobeet ({{ category.name }})</title>
  <subtitle>Latest Jobs</subtitle>
  <link href="{{ url('EnsJobeetBundle_category', { 'slug': category.slug, '_format': 'atom' }) }}" rel="self" />
  <link href="{{ url('EnsJobeetBundle_category', { 'slug': category.slug }) }}" />
  <updated>{{ category.activejobs[0].createdAt.format(constant('DATE_ATOM')) }}</updated>
  <author><name>Jobeet</name></author>
  <id>{{ feedId }}</id>

  {% for entity in category.activejobs %}
    <entry>
      <title>{{ entity.position }} ({{ entity.location }})</title>
      <link href="{{ url('ens_job_show', { 'id': entity.id, 'company': entity.companyslug, 'location': entity.locationslug, 'position': entity.positionslug }) }}" />
      <id>{{ entity.id }}</id>
      <updated>{{ entity.createdAt.format(constant('DATE_ATOM')) }}</updated>
      <summary type="xhtml">
        <div xmlns="http://www.w3.org/1999/xhtml">
          {% if entity.logo %}
            <div>
              <a href="{{ entity.url }}">
                <img src="http://{{ app.request.host }}/uploads/jobs/{{ entity.logo }}" alt="{{ entity.company }} logo" />
              </a>
            </div>
          {% endif %}
          <div>
            {{ entity.description|nl2br }}
          </div>
          <h4>How to apply?</h4>
          <p>{{ entity.howtoapply }}</p>
        </div>
      </summary>
      <author><name>{{ entity.company }}</name></author>
    </entry>
  {% endfor %}
</feed>

11 thoughts on “Symfony2 Jobeet Day 14: Feeds”

  1. Fantastic job with the tutorial – really, really helpful. Thank you for taking the time to update Jobeet for Symfony 2.

  2. I just wanted to thank you for preparing this tutorial !! I’ve been following it and it worked everything almost straight away. Well done for sharing your knowledge and thank you.

    Of course it would be great if you could carry on !! You have a bunch of fans waiting for your next move !!

  3. Nice tutorial. Thank you.

    One question though : It took you about 14 days to built the sire and the admin backend, etc… why would one choose the CMF syfony when one can get the same results and more with a CMS like Drupal (that is also PHP base) ? I don’t see the point ?

    Don’t get me wrong really thankful for the tutorial but I don’t see the point of recoding the wheel when a full community already did it …..

  4. It is a fantastic tutorial! However some of the contents are slightly out dated with the present version of Symfony. Would highly appreciate if you can come out with updated version for ‘PhpUnit Test/ functional test/Admin(sonta)’ chapters..

Leave a Reply

Your email address will not be published. Required fields are marked *