Practical symfony

Giorno 15: Feed

About

You are currently reading "Practical symfony" which is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License license.

Jobeet Links

Symfony 2.0 Preview Release

Chapter Content

Formati

Feed

Feed Ultime Offerte di Lavoro

Feed delle ultime offerte in una categoria

A domani

symfony training
Be trained by symfony experts
Apr 12: Paris (What's new in 1.3/1.4 - Français)
Apr 21: Paris (1.4 + Doctrine - Français)
Apr 28: Online (What's new in 1.3/1.4 - Français)
May 03: Paris (What's new in 1.3/1.4 - Français)
and more...

Search


powered by google
You are currently browsing "Practical symfony" in Italian for the 1.2 version - Propel edition - Switch to version: - Switch to ORM: - Switch to language:
Creative Commons License This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.
This version of symfony is not maintained anymore.
If some of your projects still use this version, consider upgrading as soon as possible.
Practical symfony (Propel edition)
Buy Practical symfony (Propel edition) from amazon.com

Ieri avete iniziato a sviluppare la vostra prima applicazione con symfony. Non fermatevi adesso. Come imparate qualcosa di nuovo su symfony provate ad aggiungere nuove feature alla vostra applicazione, rendetela pubblica e condividetela con la comunità.

Passiamo oggi a qualcosa di completamente diverso.

Se state cercando un lavoro molto probabilmente vorreste essere informati ogni volta che un'offerta viene inserita. Poiché controllare il sito web ogni ora non è molto conveniente, oggi aggiungeremo molti feed, per tenere aggiornati gli utenti di Jobeet.

Formati

Il framework symfony ha un supporto nativo per formati e tipi mime. Questo significa che gli stessi Model e Controller possono avere diversi template in base al formato richiesto. Il formato di default è HTML, tuttavia symfony supporta molti altri formati in modo nativo come txt, js, css, json, xml, rdf o atom.

Il formato può essere impostato usando il metodo setRequestFormat() dell'oggetto richiesta:

$request->setRequestFormat('xml');

Il più delle volte il formato è integrato nell'URL. In questo caso symfony lo imposterà per voi se la variabile speciale sf_format è utilizzata nella corrispondente rotta. Per la lista delle offerte l'URL è:

http://jobeet.localhost/frontend_dev.php/job

Questo URL è equivalente a:

http://jobeet.localhost/frontend_dev.php/job.html

Entrambi gli URL sono equivalenti perché le rotte generate dalla classe sfPropelRouteCollection hanno sf_format come estensione e perché il formato standard è html. Potete verificarlo personalmente utilizzando il task app:routes.

Cli

Feed

Feed Ultime Offerte di Lavoro

Supportare diversi formati è semplice quanto creare diversi template. Per creare un Atom feed per le ultime offerte inserite, create il template indexSuccess.atom.php:

<!-- apps/frontend/modules/job/templates/indexSuccess.atom.php -->
<?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>

Di default symfony cambia la risposta Content-Type in accordo al formato, per tutti i formati non-HTML il layout viene disabilitato. Per un feed Atom symfony cambia il Content-Type a application/atom+xml; charset=utf-8.

Nel footer di Jobeet aggiornate il link del feed:

<!-- apps/frontend/templates/layout.php -->
<li class="feed">
  <a href="<?php echo url_for('@job?sf_format=atom') ?>">Full feed</a>
</li>

L'URI interno è lo stesso che per la lista job con il sf_format aggiunto come variabile.

Aggiungete un <link> tag nell'head del layout, per consentire la scoperta automatica dei feed da parte del browser:

<!-- apps/frontend/templates/layout.php -->
<link rel="alternate" type="application/atom+xml" title="Latest Jobs"
  href="<?php echo url_for('@job?sf_format=atom', true) ?>" />

Per l'attributo href link viene usato un URL assoluto, grazie al secondo parametro dell'helper url_for().

Sostituiamo l'header del template Atom col codice seguente:

<!-- apps/frontend/modules/job/templates/indexSuccess.atom.php -->
<title>Jobeet</title>
<subtitle>Latest Jobs</subtitle>
<link href="<?php echo url_for('@job?sf_format=atom', true) ?>" rel="self"/>
<link href="<?php echo url_for('@homepage', true) ?>"/>
<updated><?php echo gmstrftime('%Y-%m-%dT%H:%M:%SZ', JobeetJobPeer::getLatestPost()->getCreatedAt('U')) ?></updated>
<author>
  <name>Jobeet</name>
</author>
<id><?php echo sha1(url_for('@job?sf_format=atom', true)) ?></id>

Notate l'utilizzo di U come parametro di getCreatedAt() per ottenere la data come timestamp. Per avere la data dell'ultimo post, create il metodo getLatestPost():

// lib/model/JobeetJobPeer.php
class JobeetJobPeer extends BaseJobeetJobPeer
{
  static public function getLatestPost()
  {
    $criteria = new Criteria();
    self::addActiveJobsCriteria($criteria);
 
    return JobeetJobPeer::doSelectOne($criteria);
  }
 
  // ...
}

I dati del feed possono essere generati con il seguente codice:

<!-- apps/frontend/modules/job/templates/indexSuccess.atom.php -->
<?php use_helper('Text') ?>
<?php foreach ($categories as $category): ?>
  <?php foreach ($category->getActiveJobs(sfConfig::get('app_max_jobs_on_homepage')) as $job): ?>
    <entry>
      <title>
        <?php echo $job->getPosition() ?> (<?php echo $job->getLocation() ?>)
      </title>
      <link href="<?php echo url_for('job_show_user', $job, true) ?>" />
      <id><?php echo sha1($job->getId()) ?></id>
      <updated><?php echo gmstrftime('%Y-%m-%dT%H:%M:%SZ', $job->getCreatedAt('U')) ?></updated>
      <summary type="xhtml">
       <div xmlns="http://www.w3.org/1999/xhtml">
         <?php if ($job->getLogo()): ?>
           <div>
             <a href="<?php echo $job->getUrl() ?>">
               <img src="http://<?php echo $sf_request->getHost().'/uploads/jobs/'.$job->getLogo() ?>"
                 alt="<?php echo $job->getCompany() ?> logo" />
             </a>
           </div>
         <?php endif; ?>
 
         <div>
           <?php echo simple_format_text($job->getDescription()) ?>
         </div>
 
         <h4>How to apply?</h4>
 
         <p><?php echo $job->getHowToApply() ?></p>
       </div>
      </summary>
      <author>
        <name><?php echo $job->getCompany() ?></name>
      </author>
    </entry>
  <?php endforeach; ?>
<?php endforeach; ?>

Il metodo getHost() dell'oggetto request ($sf_request) restituisce l'host corrente, che torna utile per creare un link assoluto per il logo della società.

Feed

Creando un feed, il debug è più semplice se si usano gli strumenti da linea di comando come curl o wget, in modo da vedere l'attuale contenuto del feed.

Feed delle ultime offerte in una categoria

Uno degli scopi di Jobeet è quello di aiutare le persone a trovare lavori più specializzati. Quindi abbiamo bisogno di fornire un feed per ogni categoria.

Primo, aggiorniamo la rotta category per aggiungere il supporto per i differenti formati:

// apps/frontend/config/routing.yml
category:
  url:     /category/:slug.:sf_format
  class:   sfPropelRoute
  param:   { module: category, action: show, sf_format: html }
  options: { model: JobeetCategory, type: object }
  requirements:
    sf_format: (?:html|atom)

Ora la rotta category può capire entrambi i formati html e atom. Aggiornate i link ai feed di categoria nei template:

<!-- apps/frontend/modules/job/templates/indexSuccess.php -->
<div class="feed">
  <a href="<?php echo url_for('category', array('sf_subject' => $category, 'sf_format' => 'atom')) ?>">Feed</a>
</div>
 
<!-- apps/frontend/modules/category/templates/showSuccess.php -->
<div class="feed">
  <a href="<?php echo url_for('category', array('sf_subject' => $category, 'sf_format' => 'atom')) ?>">Feed</a>
</div>

L'ultimo passo è creare il template showSuccess.atom.php. Ma visto che questo feed dovrà elencare le offerte di lavoro possiamo rifattorizzare il codice che genera i dati per il feed creando un partial _list.atom.php. Come per il formato html i partial sono specifici per il formato:

<!-- apps/frontend/job/templates/_list.atom.php -->
<?php use_helper('Text') ?>
 
<?php foreach ($jobs as $job): ?>
  <entry>
    <title><?php echo $job->getPosition() ?> (<?php echo $job->getLocation() ?>)</title>
    <link href="<?php echo url_for('job_show_user', $job, true) ?>" />
    <id><?php echo sha1($job->getId()) ?></id>
      <updated><?php echo gmstrftime('%Y-%m-%dT%H:%M:%SZ', $job->getCreatedAt('U')) ?></updated>
    <summary type="xhtml">
     <div xmlns="http://www.w3.org/1999/xhtml">
       <?php if ($job->getLogo()): ?>
         <div>
           <a href="<?php echo $job->getUrl() ?>">
             <img src="http://<?php echo $sf_request->getHost().$job->getLogo() ?>" alt="<?php echo $job->getCompany() ?> logo" />
           </a>
         </div>
       <?php endif; ?>
 
       <div>
         <?php echo simple_format_text($job->getDescription()) ?>
       </div>
 
       <h4>How to apply?</h4>
 
       <p><?php echo $job->getHowToApply() ?></p>
     </div>
    </summary>
    <author>
      <name><?php echo $job->getCompany() ?></name>
    </author>
  </entry>
<?php endforeach; ?>

Potete usare il partial _list.atom.php per semplificare il template del feed delle offerte:

<!-- apps/frontend/modules/job/templates/indexSuccess.atom.php -->
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Jobeet</title>
  <subtitle>Latest Jobs</subtitle>
  <link href="<?php echo url_for('@job?sf_format=atom', true) ?>" rel="self"/>
  <link href="<?php echo url_for('@homepage', true) ?>"/>
  <updated><?php echo gmstrftime('%Y-%m-%dT%H:%M:%SZ', JobeetJobPeer::getLatestPost()->getCreatedAt('U')) ?></updated>
  <author>
    <name>Jobeet</name>
  </author>
  <id><?php echo sha1(url_for('@job?sf_format=atom', true)) ?></id>
 
<?php foreach ($categories as $category): ?>
  <?php include_partial('job/list', array('jobs' => $category->getActiveJobs(sfConfig::get('app_max_jobs_on_homepage')))) ?>
<?php endforeach; ?>
</feed>

Infine create il template showSuccess.atom.php:

<!-- apps/frontend/modules/category/templates/showSuccess.atom.php -->
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Jobeet (<?php echo $category ?>)</title>
  <subtitle>Latest Jobs</subtitle>
  <link href="<?php echo url_for('category', array('sf_subject' => $category, 'sf_format' => 'atom'), true) ?>" rel="self" />
  <link href="<?php echo url_for('category', array('sf_subject' => $category), true) ?>" />
  <updated><?php echo gmstrftime('%Y-%m-%dT%H:%M:%SZ', $category->getLatestPost()->getCreatedAt('U')) ?></updated>
  <author>
    <name>Jobeet</name>
  </author>
  <id><?php echo sha1(url_for('category', array('sf_subject' => $category), true)) ?></id>
 
  <?php include_partial('job/list', array('jobs' => $pager->getResults())) ?>
</feed>

Come per il feed principale abbiamo bisogno della data dell'ultima offerta inserita per una categoria:

// lib/model/JobeetCategory.php
class JobeetCategory extends BaseJobeetCategory
{
  public function getLatestPost()
  {
    $jobs = $this->getActiveJobs(1);
 
    return $jobs[0];
  }
 
  // ...
}

Category Feed

A domani

Come per molte feature di symfony il supporto nativo vi permette di aggiungere feed al vostro sito senza particolari sforzi.

Oggi abbiamo migliorato l'esperienza di ricerca di lavoro. Domani vedremo come dare maggiore possibilità di inserimento a chi pubblica offerte di lavoro fornendo un Web Service.

Giorno 16: Web Service »
« Giorno 14: Il giorno pigro

Questions & Feedback

If you find a typo or an error, please register and open a ticket.

If you need support or have a technical question, please post to the official user mailing-list.

The Sensio Labs Network

Since 1998, Sensio Labs has been promoting the Open-Source software movement by providing quality web application development, training, consulting.
Sensio Labs also supports several large Open-Source projects.