programming

Symfony 1.4.20 Sessions Storage

Variabili di Sessione

Symfony facilita il salvataggio nelle varibili di sessione php tramite l’utilizzo della classe – sfUser –
in particolare:


// Per sfActions

$this->getUser()->setAttribute('nomevariabile', valore)
$this->getUser()->getAttribute('nomevariabile',se la variabile non esiste)

$this->getUser()->getAttributeHolder()->remove('nomevariabile');
$this->getUser()->getAttributeHolder()->clear();

// dal Template
$sf_user->getAttribute('nomevariabile')

Un esempio pratico:

actions.class.php


<?php
 
class contenutoActions extends sfActions // estende la classe Symfony
{ 
  public function executeFirstpage($request)// http://localhost/jobeet/web/frontend_dev.php/contenuto/firstpage
  {
    $nickname = 'Andrea';
 
    // 1. Salva nella sessione la variabile nickname con il valore Andrea
    // getUser()->setAttribute è un metodo della classe Symfony sfUser
    $this->getUser()->setAttribute('nickname', $nickname);
    return $this->renderText('Salvata la variabile di sessione nickname= '. $nickname);
  }
 
  public function executeSecondpage() // http://localhost/jobeet/web/frontend_dev.php/contenuto/secondpage
  {
    // 2. Carica la variabile di sessione nickname
    // getUser()->getAttribute è un metodo della classe Symfony sfUser
    //                                          variabile, se la variabile non esiste
    $nickname = $this->getUser()->getAttribute('nickname', 'Visitatore Anonimo');
    return $this->renderText($nickname); // render della variabile o di 'Visitatore Anonimo'
  }
  
  public function executeThirdpage() // http://localhost/jobeet/web/frontend_dev.php/contenuto/thirdpage
  {
    // richiama il template che carica direttamente dal suo interno la variabile di sessione
  }
  
  public function executeRemovenickname() // http://localhost/jobeet/web/frontend_dev.php/contenuto/removenickname
  {
    // getUser()->getAttributeHolder() è il contenitore di tutti i parametri
    // rimuove solo la variabile nickname
    $this->getUser()->getAttributeHolder()->remove('nickname');
    return $this->renderText('Rimosso nickname');
  }
 
  public function executeCleanup() // http://localhost/jobeet/web/frontend_dev.php/contenuto/cleanup
    // rimuove tutte le variabili di sessione
    $this->getUser()->getAttributeHolder()->clear();
    return $this->renderText('Rimosse tutte le variabili di sessione');
  }
}// END class

thirdpageSuccess.php


Hello, <?php echo $sf_user->getAttribute('nickname') ?>

Variabili di Sessione Flash

Symfony memorizza in sessione anche dei dati che definisce flash.
Le variabili flash vengono automaticamente cancellate dopo essere state caricate, non è necessario eliminarle esplicitamente dalla sessione.

actions.class.php


<?php
 
class contenutoActions extends sfActions // estende la classe Symfony
{ 
  public function executeThirdpage() // http://localhost/jobeet/web/frontend_dev.php/contenuto/thirdpage
  {
      $value = 'Questa è una nota Flash';
      $this->getUser()->setFlash('notice', $value);
  }
  
}// END class

thirdpageSuccess.php


<?php echo $sf_user->getFlash('notice') ?>

Ref: http://symfony.com/legacy/doc/gentle-introduction/1_4/it/06-Inside-the-Controller-Layer

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony 1.4.20 Sessions Storage

Symfony 1.4.22 – Controller – Actions – preExecute – execute – postExecute – CustomMethod

Symfony mette a dispossizione dei metodi speciali all’interno della classe sfActions per dare un ordine di esecuzione particolare alle nostre operazioni.

apps/frontend/modules/contenuto/actions/actions.class.php


<?php
 
class contenutoActions extends sfActions // estende la classe Symfony
{
  public function preExecute()
  {
    // 1. Il codice inserito qui viene eseguito all'inizio di ogni azione
    echo "Codice di preExecute<br>";
  }
    
  public function executePageone($request) // http://localhost/jobeet/web/frontend_dev.php/contenuto/pageone
  {
      $this->myCustomMethod();  // I metodi della classe azione sono accessibili
      
      return $this->renderText("Codice di executePageone<br>"); // 4. ultimo ad essere eseguito
  }
  
  public function postExecute()
  {
    // 3. Il codice inserito qui viene eseguito alla fine di ogni azione
    echo "Codice di postExecute<br>";
  }
 
  protected function myCustomMethod()
  {
    // 2. È possibile aggiungere i propri metodi, ammesso che non inizino con "execute"
    // In questo caso è consigliabile dichiararli protetti o privati
    echo "Codice di myCustomMethod<br>";
  }
}// END class

Renderizza:

Codice di preExecute
Codice di myCustomMethod
Codice di postExecute
Codice di executePageone

Reference:
http://symfony.com/legacy/doc/gentle-introduction/1_4/it/06-Inside-the-Controller-Layer

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony 1.4.22 – Controller – Actions – preExecute – execute – postExecute – CustomMethod

Symfony 1.4.20 – Database – Caricare i Dati Iniziali

Come caricare automaticamente i dati iniziali nel database utilizzando Symfony 1.4.22

0. Continuiamo dalla lezione precedente a: http://www.lucedigitale.com/blog/creare-un-database-orm-doctrine/

1. Creiamo un file YAML con dei dati dummies, creiamo wamp64/www/jobeet/data/fixtures/categories.yml


# data/fixtures/categories.yml
JobeetCategory:
  design:
    name: Design
  programming:
    name: Programming
  manager:
    name: Manager
  administrator:
    name: Administrator
 
# data/fixtures/jobs.yml
JobeetJob:
  job_sensio_labs:
    JobeetCategory: programming
    type:         full-time
    company:      Sensio Labs
    logo:         /uploads/jobs/sensio_labs.png
    url:          http://www.sensiolabs.com/
    position:     Web Developer
    location:     Paris, France
    description:  |
      You've already developed websites with symfony and you want to work
      with Open-Source technologies. You have a minimum of 3 years
      experience in web development with PHP or Java and you wish to
      participate to development of Web 2.0 sites using the best
      frameworks available.
    how_to_apply: |
      Send your resume to fabien.potencier [at] sensio.com
    is_public:    true
    is_activated: true
    token:        job_sensio_labs
    email:        job@example.com
    expires_at:   '2008-10-10'
 
  job_extreme_sensio:
    JobeetCategory:  design
    type:         part-time
    company:      Extreme Sensio
    logo:         /uploads/jobs/extreme_sensio.png
    url:          http://www.extreme-sensio.com/
    position:     Web Designer
    location:     Paris, France
    description:  |
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
      eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
      enim ad minim veniam, quis nostrud exercitation ullamco laboris
      nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in.
 
      Voluptate velit esse cillum dolore eu fugiat nulla pariatur.
      Excepteur sint occaecat cupidatat non proident, sunt in culpa
      qui officia deserunt mollit anim id est laborum.
    how_to_apply: |
      Send your resume to fabien.potencier [at] sensio.com
    is_public:    true
    is_activated: true
    token:        job_extreme_sensio
    email:        job@example.com
    expires_at:   '2008-10-10'

2. Carichiamo i dati nel DB
cmd.exe -> C:\wamp64\www\jobeet>symfony doctrine:data-load

Aprire phpMyAdmin, ora i dati sono presenti nel database

3. Generiamo form, filtri, modelli, e cancelliamo e ricreiamo il database con tutte le tabelle.
cmd.exe -> C:\wamp64\www\jobeet>symfony doctrine:build –all –and-load

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony 1.4.20 – Database – Caricare i Dati Iniziali

Symfony 1.4.20 – Database – Form Accesso Dati

Creare automaticamente con Symfony un Form per accedere ai dati del dababase.

In Symfony un progetto è composto da applicazioni suddivise in moduli, ad esempio:

– jobeet/apps/frontend/modules/contenuto
– jobeet/apps/frontend/modules/job
– jobeet/apps/frontend/modules/nome altro modulo …

– jobeet/apps/nome altra app…

1. Generiamo automaticamente il codice php per la gestione di un modulo di nome ‘job’
cmd.exe -> C:\wamp64\www\jobeet>symfony doctrine:generate-module –with-show –non-verbose-templates frontend job JobeetJob

verrà creato automaticamente:

apps/frontend/modules/job/actions/
apps/frontend/modules/job/templates/

in particolare apps/frontend/modules/job/actions/action.class.php


<?php

/**
 * job actions.
 *
 * @package    symfony
 * @subpackage job
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class jobActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->jobeet_jobs = Doctrine_Core::getTable('JobeetJob')
      ->createQuery('a')
      ->execute();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->jobeet_job = Doctrine_Core::getTable('JobeetJob')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->jobeet_job);
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new JobeetJobForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new JobeetJobForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($jobeet_job = Doctrine_Core::getTable('JobeetJob')->find(array($request->getParameter('id'))), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
    $this->form = new JobeetJobForm($jobeet_job);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($jobeet_job = Doctrine_Core::getTable('JobeetJob')->find(array($request->getParameter('id'))), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
    $this->form = new JobeetJobForm($jobeet_job);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($jobeet_job = Doctrine_Core::getTable('JobeetJob')->find(array($request->getParameter('id'))), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
    $jobeet_job->delete();

    $this->redirect('job/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $jobeet_job = $form->save();
      $this->redirect('job/edit?id='.$jobeet_job->get());
    }
  }
}

Puntare il browser a: http://localhost/jobeet/web/index.php/job per vedere il form in azione

2. Personalizziamo il template a: jobeet/apps/frontend/templates/layout.php


<!-- apps/frontend/templates/layout.php -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Jobeet - Your best job board</title>
    <link rel="shortcut icon" href="/favicon.ico" />
    <?php include_javascripts() ?>
    <?php include_stylesheets() ?>
  </head>
  <body>
    <div id="container">
      <div id="header">
        <div class="content">
          <h1><a href="<?php echo url_for('job/index') ?>">
            <img src="/legacy/images/logo.jpg" alt="Jobeet Job Board" />
          </a></h1>
 
          <div id="sub_header">
            <div class="post">
              <h2>Ask for people</h2>
              <div>
                <a href="<?php echo url_for('job/index') ?>">Post a Job</a>
              </div>
            </div>
 
            <div class="search">
              <h2>Ask for a job</h2>
              <form action="" method="get">
                <input type="text" name="keywords"
                  id="search_keywords" />
                <input type="submit" value="search" />
                <div class="help">
                  Enter some keywords (city, country, position, ...)
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
 
      <div id="content">
        <?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_notice">
            <?php echo $sf_user->getFlash('error') ?>
          </div>
        <?php endif; ?>
 
        <div class="content">
          <?php echo $sf_content ?>
        </div>
      </div>
 
      <div id="footer">
        <div class="content">
          <span class="symfony">
            <img src="/legacy/images/jobeet-mini.png" />
            powered by <a href="/">
            <img src="/legacy/images/symfony.gif" alt="symfony framework" />
            </a>
          </span>
          <ul>
            <li><a href="">About Jobeet</a></li>
            <li class="feed"><a href="">Full feed</a></li>
            <li><a href="">Jobeet API</a></li>
            <li class="last"><a href="">Affiliates</a></li>
          </ul>
        </div>
      </div>
    </div>
  </body>
</html>

Incompatibilità PHP 5.5

Puntare il browser a: http://localhost/jobeet/web/frontend_dev.php/job

preg_replace() è deprecata, andrebbe sostituita nelle librerie Symfony con preg_replace_callback(), cancelliamo i warning testuali generati nel codice e tentiamo di correggere l’errore (https://gist.github.com/gitllermopalafox/0a8b60eaafede6af0b75)

Correggere C:\wamp64\bin\php\php5.6.25\pear\symfony\response\sfWebResponse.class.php riga 409


protected function normalizeHeaderName($name)
  {
    // return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($name)), '_', '-'));    

    return preg_replace_callback(
                  '/\-(.)/', 
                  function ($matches) {
                    return '-'.strtoupper($matches[1]);
                  }, 
                  strtr(ucfirst(strtolower($name)), '_', '-')
        );
  }  

Correggere C:\wamp64\bin\php\php5.6.25\pear\symfony\util\sfToolkit.class.php riga 362:


public static function pregtr($search, $replacePairs)
  {
    // return preg_replace(array_keys($replacePairs), array_values($replacePairs), $search);
    foreach($replacePairs as $pattern => $replacement)
        $search = preg_replace_callback(
                    $pattern, 
                    function ($matches) use ($replacement){
                        if(array_key_exists(1, $matches)){ $replacement = str_replace("\\1", $matches[1], $replacement);}
                        if(array_key_exists(2, $matches)){ $replacement = str_replace("\\2", $matches[2], $replacement);}
                        return $replacement;
                    }, 
                    $search
                );
    return $search;
  }

By |PHP, Symfony, Web Business|Commenti disabilitati su Symfony 1.4.20 – Database – Form Accesso Dati

Symfony 1.4.22 – Contact Form Semplice

Come creare con Symfony 1.4.22 un semplice form per i contatti.

Form dentro al Controller

1. apps/modules/contenuto/actions/actions.class.php


<?php

class contenutoActions extends sfActions // estende la classe Symfony
{
  public function executeContact($request) // crea la pagina http://localhost/jobeet/web/contenuto/contact
    {
      $this->form = new sfForm(); // istanzia la classe di Symfony per la creazione dei form
      // setta i widget, cioè il tipo di campo e i parametri
      $this->form->setWidgets(array(
        'name'    => new sfWidgetFormInputText(),
        'email'   => new sfWidgetFormInputText(array('default' => 'me@example.com')),
        'subject' => new sfWidgetFormChoice(array('choices' => array('Subject A', 'Subject B', 'Subject C'))),
        'message' => new sfWidgetFormTextarea(),
      ));
      // la richiesta inviata a contactSuccess.php sarà un oggetto composto da array
      // l'oggetto è contenuto nella variabile  - form - in contactSuccess.php sarà - echo $form -
    }
}// END class

2. apps/modules/contenuto/templates/contactSuccess.php


<?php echo $form->renderFormTag('contenuto/contact') ?>
  <table>
    <?php echo $form ?>
    <tr>
      <td colspan="2">
        <input type="submit" />
      </td>
    </tr>
  </table>
</form>

3. Puntare il browser a: http://localhost/jobeet/web/frontend_dev.php/contenuto/contact


<form action="/frontend_dev.php/contenuto/contact" method="POST">
  <table>
    <tr>
      <th><label for="name">Name</label></th>
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    <tr>
      <th><label for="email">Email</label></th>
      <td><input type="text" name="email" id="email" value="me@example.com" /></td>
    </tr>
    <tr>
      <th><label for="subject">Subject</label></th>
      <td>
        <select name="subject" id="subject">
          <option value="0">Subject A</option>
          <option value="1">Subject B</option>
          <option value="2">Subject C</option>
        </select>
      </td>
    </tr>
    <tr>
      <th><label for="message">Message</label></th>
      <td><textarea rows="4" cols="30" name="message" id="message"></textarea></td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="submit" />
      </td>
    </tr>
  </table>
</form>

Reference:
http://symfony.com/legacy/doc/gentle-introduction/1_4/it/10-forms

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony 1.4.22 – Contact Form Semplice