- Fri
- 8
- Aug
- 08
Costruire un’applicazione reale con Zend Framework ( parte 4 )
Di in Php, Zend Framework Controls: +-close
I Modelli
Eccoci giunti alla realizzazione del nostro primo modello.
Se non l’avete ancora fatto, dovrete creare il database paesidelmondo in cui andrete a creare 2 tabelle ed inserire alcuni dati. Niente paura, basta far eseguire la seguente query al vostro db e tutto sarà pronto per cominciare:
CREATE TABLE `paesi` ( `id` int(11) NOT NULL auto_increment, `nome` varchar(99) NOT NULL, `provincia` varchar(99) NOT NULL, `inserimento_data` datetime NOT NULL, `inserimento_user_id` int(11) NOT NULL, `inserimento_ip` varchar(15) NOT NULL, `modifica_data` timestamp NULL default NULL on update CURRENT_TIMESTAMP, `modifica_user_id` varchar(11) default NULL, `modifica_ip` varchar(15) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dump dei dati per la tabella `paesi` -- INSERT INTO `paesi` (`id`, `nome`, `provincia`, `inserimento_data`, `inserimento_user_id`, `inserimento_ip`, `modifica_data`, `modifica_user_id`, `modifica_ip`) VALUES (1, 'Chieri', 'Torino', '2008-08-06 17:26:05', 1, '127.0.0.1', '2008-08-06 17:26:41', NULL, NULL), (2, 'Pessione', 'Torino', '2008-08-06 17:26:32', 1, '127.0.0.1', '2008-08-06 17:26:41', NULL, NULL); -- -------------------------------------------------------- -- -- Struttura della tabella `recensioni` -- CREATE TABLE `recensioni` ( `id` int(11) NOT NULL auto_increment, `id_paesi` int(11) NOT NULL, `descrizione` mediumtext NOT NULL, `inserimento_data` datetime NOT NULL, `inserimento_user_id` int(11) NOT NULL, `inserimento_ip` varchar(15) NOT NULL, `modifica_data` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP, `modifica_user_id` int(11) default NULL, `modifica_ip` varchar(15) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dump dei dati per la tabella `recensioni` -- INSERT INTO `recensioni` (`id`, `id_paesi`, `descrizione`, `inserimento_data`, `inserimento_user_id`, `inserimento_ip`, `modifica_data`, `modifica_user_id`, `modifica_ip`) VALUES (1, 1, ' Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. \r\n\r\n It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. \r\n\r\n The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli, but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. Pityful a rethoric question ran over her cheek, then ', '2008-08-06 17:27:44', 1, '127.0.0.1', '0000-00-00 00:00:00', NULL, NULL), (2, 2, ' Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. \r\n\r\n At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles. Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues. \r\n\r\n It va esser tam simplic quam Occidental in fact, it va esser Occidental. A un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico dit me que Occidental es. Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles. ', '2008-08-06 17:28:21', 1, '127.0.0.1', '0000-00-00 00:00:00', NULL, NULL);
Il primo modello
Il primo modello che andremo ad implementare recupererà i dati all’interno della tabella ‘paesi’. Il file, chiamato Paesi.php deve essere creato all’interno di application\models. Il seguente è il suo contenuto:
< ?php
class Paesi extends Zend_Db_Table
{
function fetchLatest($count = 10) {
return $this->fetchAll(null,'inserimento_data DESC', $count);
}
}
Per fare in modo che tutto funzioni, il motore php sul nostro server dovrà avere caricato le estensioni php_pdo e php_pdo_mysql, in quanto, per questa applicazione, abbiamo specificato l’utilizzo del driver pdo nel file di configurazione config.ini.
Il metodo fetchAll
Il metodo fetchAll recupera tutte le righe e tutte le colonne di un resultset. Sintassi:
fetchAll($where, $order, $count, $offset);
Nel nostro esempio abbiamo inserito questo metodo all’interno di fetchLatest, nome che abbiamo dato ad un metodo che recupera gli ultimi X record inseriti ( 10 di default ).
IndexController
Modifichiamo quindi la indexAction del nostro IndexController.
public function indexAction(){
$this->view->pageTitle = 'Paesidelmondo Application Example';
$this->view->bodyTitle = 'Paesidelmondo';
$paesi = new Paesi();
$this->view->paesi = $paesi->fetchLatest();
}
In questo modo creiamo la variabile paesi all’interno della view ( $this->view->paesi ), contenente un array di oggetti che potremo ciclare nel nostro index.phtml.
Index.phtml
Il seguente è il nuovo contenuto di index.html
<h2>< ?php echo $this->escape($this->bodyTitle);?></h2>
< ?php // echo $this->bodyContent;?>
< ?php if(count($this->paesi)): ?>
<table>
< ?php foreach($this->paesi as $paese): ?>
<tr>
<td><a href="<?php echo $this->baseUrl;?>/paese/< ?php
echo $paese->id; ?>">< ?php
echo $this->escape($paese->nome); ?></a></td>
<td>< ?php echo $this->displayDate($paese->modifica_data); ?></td>
</tr>
< ?php endforeach;?>
</table>
< ?php endif;?>
Per comodità ho eliminato dalla visualizzazione il contenuto di bodyContent in modo da concentrarci meglio sui dati estrapolati dal database.
Il codice credo che sia autoesplicativo, l’unica nota da fare è sul metodo displayDate, metodo facente parte di un nuovo helper, DisplayDate.php da inserire all’interno di application\views\helpers
Display date
Il seguente è il codice di DisplyDate.php
< ?php
class Zend_View_Helper_DisplayDate {
function displayDate($time, $format='%d %B %Y'){
$timestamp = strtotime($time);
return strftime($format, $timestamp);
}
}
Questo metodo trasforma le date ritornate dal db in una data più facilmente leggibile.
Infine, prima di poter testare il tutto, aggiungiamo una semplice linea di codice al nostro bootstrap index.php, ovvero una nuova include_path, quella per i modelli.
// Blocco 1 [ ... ] // Blocco 1b set_include_path(ZEND_ROOT.'application/models'.PATH_SEPARATOR.get_include_path()); [ ... ]
Non ci rimane che testare il tutto. Per qualsiasi domanda potete postare i vostri commenti al termine di ogni articolo.
Ovviamente non è finita qui.
Ancora non ho deciso cosa tratterà la quinta parte, che comunque sarà disponibile il più presto possibile.
Related posts:
- Zend Framework: gestione dei moduli ed esempio modulo di amministrazione Come usare Zend_Layout per la gestione dei moduli In quest'articolo...
- Zend Framework: Zend_Form con ReCaptcha Utilizzare il webservice ReCaptcha per validare i form ReCaptcha è...
- Zend Framework: introduzione al componente Zend_Form Creare form web con Zend Form Con Zend Framework possiamo...
- Neobazaar annunci gratuiti: esempio di una applicazione sviluppata con Zend Framework Nasce Neobazaar.com, annunci gratuiti in Italia: interamente sviluppato con Zend...
Related posts brought to you by Yet Another Related Posts Plugin.











