- Wed
- 6
- Aug
- 08
Costruire un’applicazione reale con Zend Framework ( parte 2 )
Di in Php, Zend Framework Controls: +-close
Two Step View
In un gran numero di siti accade che alcune parti del layout cambino poco o non cambino proprio al cambiare della pagina. Per ogni azione richiesta si avrà il relativo controller che avrà la relativa vista che sarà un file .phtml. Per mantenere il sito uniforme, una possibile soluzione sarebbe di includere all’interno di ogni file .phtml un codice del genere:
< ?php echo $this->render('header.phtml'); ?>
< ?php echo $this->title; ?>
< ?php echo $this->content; ?>
< ?php echo $this->render('footer.phtml'); ?>
Siccome la ridondanza del codice è una cosa che ai programmatori non dovrebbe piacere per vari motivi, giunge in nostro aiuto la Two Step View.
La Two Step View consiste nel separare le parti comuni del nostro layout con la parte che effettivamente sarà aggiornata al cambiare della pagina.
Apriamo quindi il file IndexController.php e modifichiamo il suo contenuto con il seguente:
class IndexController extends Zend_Controller_Action {
public function init(){
$response = $this->getResponse();
$response->insert('sidebar', $this->view->render('sidebar.phtml'));
}
public function indexAction(){
$this->view->pageTitle = 'Paesidelmondo Application Example';
$this->view->bodyTitle = '
Paesidelmondo
';
$this->view->bodyContent = '
One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible
vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches
into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared
with the size of the rest of him, waved about helplessly as he looked. "What\'s happened to me? " he thought. It wasn\'t a dream.
His room, a proper human room although a little too small, lay peacefully between its four familiar walls. A collection of textile samples
lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated
magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff
that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather.
Drops of rain could be heard hitting the pane, which made him feel quite sad. "How about if I sleep a little bit longer and forget all
this nonsense", he thought, but that was something he was unable to do because he was used to sleeping on his right, and in his present state
couldn\'t get into that position. However hard he threw himself onto his right, he always rolled back to where he was. He must have tried it
a hundred times, shut his eyes so that he wouldn\'t have to look at the floundering legs, and only stopped when he began to feel a mild, dull
pain there that he had never felt before. "Oh, God", he thought, "what a strenuous career it is that I\'ve chosen! Travelling day in and day
out. Doing business like this takes much more effort than doing your own business at home, and on top of that there\'s the curse of travelling,
worries about making train connections, bad and irregular food, contact with different people all the time so that you can never get to know
anyone or become friendly with them. It can all go to Hell! " He felt a slight itch
';
}
}
Apriamo o creiamo in caso ancora non l’avessimo fatto il file sidebar.phtml all’interno di views/scripts.
Per questo esempio, creeremo un file molto molto semplice:
Menù
- Pagina 1
- Pagina 2
- Pagina 3
- Pagina 4
- Pagina 5
- Pagina 6
- Pagina 7
- Pagina 8
Il file index.phtml su views\scripts sarà composto da 2 linee di codice:
< ?php echo $this->bodyTitle ;?> < ?php echo $this->bodyContent ;?>
Ed infine il file layout.phtml salvato all’interno di views\layouts :
< !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>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>< ?php echo $this->escape($this->pageTitle); ?></title>
<link rel="stylesheet" href="<?php echo $this->baseUrl(); ?>/css/main.css" type="text/css">
</link></head>
<body>
<!-- start sidebar -->
<div id="sidebar">< ?php echo $this->layout()->sidebar; ?></div>
<!-- end sidebar -->
<!-- start content -->
<div id="content">< ?php echo $this->layout()->content ?></div>
<!-- end content -->
</body>
</html>
Che cosa è successo? Come potete notare nel file IndexController.php, abbiamo aggiunto il metodo init, che intercetta l’oggetto $response e gli inietta sidebar.phtml al cui contenuto potremo accedere tramite la chiamata $this->layout()->sidebar; all’interno del file layout.phtml.
Abbiamo quindi risolto il problema della ridondanza del codice in maniera elegante.
Nel nostro layout abbiamo inoltre utilizzato un view helper, baseUrl, utile per caricare il css.
Il seguente è il codice del baseUrl view helper, da inserire nella directory degli helper, che di default su zend framewor si trova in application\views\helpers
BaseUrl.php
< ?php
class Zend_View_Helper_BaseUrl
{
function baseUrl(){
$fc = Zend_Controller_Front::getInstance();
$request = $fc->getRequest();
return $request->getBaseUrl();
}
}
Infine, per concludere con questa seconda parte, l’ultima modifica da implementare risiede nel file index.php, ovvero il nostro file di bootstrap. Sostituite questo codice:
// Blocco 4 $frontController->dispatch();
con questo codice:
// Blocco 4
try {
$frontController->dispatch();
} catch(Exception $e) {
echo nl2br($e->__toString());
}
Questa modifica è autoesplicativa, non fa altro che inserire il metodo dispatch() all’interno di un costrutto try/catch in modo da catturare un errore nell’eventualità che si presenti.
Links
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 è...
- Neobazaar annunci gratuiti: esempio di una applicazione sviluppata con Zend Framework Nasce Neobazaar.com, annunci gratuiti in Italia: interamente sviluppato con Zend...
- Zend Framework: introduzione al componente Zend_Form Creare form web con Zend Form Con Zend Framework possiamo...
Related posts brought to you by Yet Another Related Posts Plugin.












[...] Two Step View per la gestione dei layouts [...]
Sto mnuovendo i primi passi con ZF, e seguendo punto per punto la guida non visualizzo correttamente la pagina.
Non va aggiunta nel bootstrap una riga del tipo:
Zend_Layout::startMvc(array(’layoutPath’ => ‘../application/views/layouts’));
Complimenti per la guida, veramente ben fatta.
Questo articolo è così vecchio che a dire il vero non saprei risponderti.
In ogni caso, se leggi l’articolo indicato nel commeno #1 di questa pagina, c’è il listato degli articoli su zend framework, e in uno di questi ( è indicato quale ), c’è una applicazione intera da scaricare.
Si, ho visto la data;-)
Stavo solamanete cercando di capire se mi era sfuggito qualche passaggio…
Comunque aggiungendo quella riga funziona tutto!
Grazie ancora