149
Zend Framework 2 ciò che facevo con ZF1 Zend Framework Day – Milano – 01/02/2013 Fare con

Fare con Zend Framework 2 ciò che facevo con ZF1

Embed Size (px)

DESCRIPTION

Introduzione a Zend Framework 2 per chi proviene da Zend Framework 1, tenuta allo Zend Framework Day di Milano del 01/02/2013. Introduzione alle nuove caratteristiche e pattern architetturali di ZF2 Zend Framework 2 non è l'evoluzione di ZF, ma un progetto nuovo: il codice è stato riscritto e poche sono le parti in comune con la versione precedente. Lo sviluppatore abituato a ZF1 non ha vita facile, ed è fondato il timore di dover imparare tutto da capo. In questo talk vediamo come cambiare le vecchie abitudini di sviluppatori ZF1, per sfruttare al meglio le potenzialità del nuovo strumento. Attraverso esempi concreti, in cui vedremo all'opera i nuovi pattern e le best practice, mostriamo come - partendo con il piede giusto - il passaggio a ZF2 possa essere meno traumatico del previsto. Il talk è orientato soprattutto a chi già conosce ZF1, ma gli argomenti affrontati possono essere utili anche a chi si avvicina a ZF per la prima volta.

Citation preview

Page 1: Fare con Zend Framework 2 ciò che facevo con ZF1

Zend Framework 2 ciò che facevo con ZF1

Zend Framework Day – Milano – 01/02/2013

Fare con

Page 2: Fare con Zend Framework 2 ciò che facevo con ZF1

2

@maraspin

Page 3: Fare con Zend Framework 2 ciò che facevo con ZF1

3

http://www.mvassociati.it/

Page 4: Fare con Zend Framework 2 ciò che facevo con ZF1

4

http://friuli.grusp.org/

Page 5: Fare con Zend Framework 2 ciò che facevo con ZF1
Page 6: Fare con Zend Framework 2 ciò che facevo con ZF1

brutto_esempio.php <?php

echo '<html><body>';

$caldaia=$_GET['caldaia'];

$mysqli = new mysqli("localhost", "user", "pwd", "mva");

$query = "SELECT * FROM cespiti WHERE id =".$caldaia;

$result = $mysqli->query($query);

while ($row = $result->fetch_assoc()) {

?><div><?php echo $row["nome, temperatura"]); ?></div>

<?php } ?>

<?php

$result->free();

$mysqli->close();

echo '</html></body>';

?>

Page 7: Fare con Zend Framework 2 ciò che facevo con ZF1

IL “FENOMENO”

Page 8: Fare con Zend Framework 2 ciò che facevo con ZF1

AGGIORNAMENTO

Page 9: Fare con Zend Framework 2 ciò che facevo con ZF1

9

Page 10: Fare con Zend Framework 2 ciò che facevo con ZF1

LA SEGRETARIA

Page 11: Fare con Zend Framework 2 ciò che facevo con ZF1

UFF. TECNICO

Page 12: Fare con Zend Framework 2 ciò che facevo con ZF1

PRODUZIONE

Page 13: Fare con Zend Framework 2 ciò che facevo con ZF1

ACCOUNT

Page 14: Fare con Zend Framework 2 ciò che facevo con ZF1

14

Com’è strutturata l’azienda?

Page 15: Fare con Zend Framework 2 ciò che facevo con ZF1

15

Che in un’applicazione…

Page 16: Fare con Zend Framework 2 ciò che facevo con ZF1

16

MVC

Page 17: Fare con Zend Framework 2 ciò che facevo con ZF1

17

Flusso MVC

Page 18: Fare con Zend Framework 2 ciò che facevo con ZF1

18

Routing

Page 19: Fare con Zend Framework 2 ciò che facevo con ZF1

19

Interazione con il modello

Page 20: Fare con Zend Framework 2 ciò che facevo con ZF1

20

Il layer di presentazione

Page 21: Fare con Zend Framework 2 ciò che facevo con ZF1

21

Risultato all’utente

Page 22: Fare con Zend Framework 2 ciò che facevo con ZF1

22

Cosa ci manca?

Page 23: Fare con Zend Framework 2 ciò che facevo con ZF1

23

Vorremmo una situazione così

Page 24: Fare con Zend Framework 2 ciò che facevo con ZF1

24

Disaccoppiamento

Page 25: Fare con Zend Framework 2 ciò che facevo con ZF1

I MODULI

Page 26: Fare con Zend Framework 2 ciò che facevo con ZF1

26

Permettono questo

Page 27: Fare con Zend Framework 2 ciò che facevo con ZF1

27

Page 28: Fare con Zend Framework 2 ciò che facevo con ZF1

Come installare ZF2?

28

Page 29: Fare con Zend Framework 2 ciò che facevo con ZF1

THE SKELETON APP

Page 30: Fare con Zend Framework 2 ciò che facevo con ZF1

30

Cloning

git clone git://github.com/zendframework/ZendSkeletonApplication.git

Page 31: Fare con Zend Framework 2 ciò che facevo con ZF1

31

Page 32: Fare con Zend Framework 2 ciò che facevo con ZF1

composer.json {

"name": "zendframework/skeleton-application",

"description": "Skeleton Application for ZF2",

"license": "BSD-3-Clause",

"keywords": [

"framework",

"zf2"

],

"homepage": "http://framework.zend.com/",

"require": {

"php": ">=5.3.3",

"zendframework/zendframework": "2.*"

}

}

Page 33: Fare con Zend Framework 2 ciò che facevo con ZF1

composer.json {

"name": "zendframework/skeleton-application",

"description": "Skeleton Application for ZF2",

"license": "BSD-3-Clause",

"keywords": [

"framework",

"zf2"

],

"homepage": "http://framework.zend.com/",

"require": {

"php": ">=5.3.3",

"zendframework/zendframework": "2.*"

}

}

Page 34: Fare con Zend Framework 2 ciò che facevo con ZF1

34

Installazione

cd ZendSkeletonApplication

php composer.phar install

Page 35: Fare con Zend Framework 2 ciò che facevo con ZF1

35

Installazione

cd ZendSkeletonApplication

php composer.phar install

> Installing zendframework/zendframework (dev-master)

Page 36: Fare con Zend Framework 2 ciò che facevo con ZF1

Come impostare il progetto?

36

Page 37: Fare con Zend Framework 2 ciò che facevo con ZF1

37

Struttura delle Cartelle

Page 38: Fare con Zend Framework 2 ciò che facevo con ZF1

38

Struttura delle Cartelle

Configurazione Applicazione

Page 39: Fare con Zend Framework 2 ciò che facevo con ZF1

39

Struttura delle Cartelle

Misc (cache, uploads, …)

Page 40: Fare con Zend Framework 2 ciò che facevo con ZF1

40

Struttura delle Cartelle

Moduli

Page 41: Fare con Zend Framework 2 ciò che facevo con ZF1

41

Struttura delle Cartelle

Moduli

Page 42: Fare con Zend Framework 2 ciò che facevo con ZF1

42

Namespace Module.php Modulo

Page 43: Fare con Zend Framework 2 ciò che facevo con ZF1

43

Struttura delle Cartelle

Modulo Application

Page 44: Fare con Zend Framework 2 ciò che facevo con ZF1

44

Struttura delle Cartelle

Parte pubblica

Page 45: Fare con Zend Framework 2 ciò che facevo con ZF1

DOCUMENT ROOT

Page 46: Fare con Zend Framework 2 ciò che facevo con ZF1

DOCUMENT ROOT

Page 47: Fare con Zend Framework 2 ciò che facevo con ZF1
Page 48: Fare con Zend Framework 2 ciò che facevo con ZF1

Come funziona il bootstrap?

48

Page 49: Fare con Zend Framework 2 ciò che facevo con ZF1

index.php <?php

/**

* This makes our life easier when dealing with paths. Everything is

* relative to the application root now.

*/

chdir(dirname(__DIR__));

// Setup autoloading

require 'init_autoloader.php';

// Run the application!

Zend\Mvc\Application::init(require 'config/application.config.php')->run();

Page 50: Fare con Zend Framework 2 ciò che facevo con ZF1

Configurazione

50

config/application.config.php

Page 51: Fare con Zend Framework 2 ciò che facevo con ZF1

config/application.config.php <?php

return array(

'modules' => array(

'Application',

),

[...]

);

Elenco dei moduli attivati

Page 52: Fare con Zend Framework 2 ciò che facevo con ZF1

Configurazione

52

Page 53: Fare con Zend Framework 2 ciò che facevo con ZF1

Module.config.php <?php [...]

return array(

'router' => array('routes' => array([…]),

),

'service_manager' => array(

'factories' => array(

'translator' => Zend\I18n\Translator\TranslatorServiceFactory',

),),

[...]

'controllers' => array(

'invokables' => array(

'Application\Controller\Index‘=>'Application\Controller\IndexController'

),),

'view_manager' => array(

[...]

),

);

Page 54: Fare con Zend Framework 2 ciò che facevo con ZF1

Configurazione

54

Page 55: Fare con Zend Framework 2 ciò che facevo con ZF1

Module.php <?php [...]

class Module implements

AutoloaderProviderInterface,

ConfigProviderInterface,

ServiceProviderInterface {

public function getAutoloaderConfig() {[...]}

public function getConfig($env = null) {

return include __DIR__ . '/config/module.config.php';

}

public function getControllerPluginConfig() {[...]}

public function getViewHelperConfig() {[...]}

public function getServiceConfig() {[...]}

}

Page 56: Fare con Zend Framework 2 ciò che facevo con ZF1

Configurazione

56

Page 57: Fare con Zend Framework 2 ciò che facevo con ZF1

Configurazione

57

Page 58: Fare con Zend Framework 2 ciò che facevo con ZF1

BOOTSTRAP

Page 59: Fare con Zend Framework 2 ciò che facevo con ZF1

ROUTING

Page 60: Fare con Zend Framework 2 ciò che facevo con ZF1

Dall’url al codice return array( […]

'routes'=> array(

[…]

'route' => '/sostituiscilampadina',

'defaults' => array(

'controller' => 'Application\Controller\Elettricista',

'action' => ‘sostlampadina',

)

[…]

),

'controllers' => array(

'invokables' => array(

'App\Controller\Elettricista' => 'App\Controller\ElettricistaController',

),

),

)

Page 61: Fare con Zend Framework 2 ciò che facevo con ZF1

Dall’url al codice return array( […]

'routes'=> array(

[…]

'route' => '/sostituiscilampadina',

'defaults' => array(

'controller' => 'Application\Controller\Elettricista',

'action' => ‘sostlampadina',

)

[…]

),

'controllers' => array(

'invokables' => array(

'App\Controller\Elettricista' => 'App\Controller\ElettricistaController',

),

),

)

Page 62: Fare con Zend Framework 2 ciò che facevo con ZF1

Dall’url al codice return array( […]

'routes'=> array(

[…]

'route' => '/sostituiscilampadina',

'defaults' => array(

'controller' => 'Application\Controller\Elettricista',

'action' => ‘sostlampadina',

)

[…]

),

'controllers' => array(

'invokables' => array(

'App\Controller\Elettricista' => 'App\Controller\ElettricistaController',

),

),

)

Page 63: Fare con Zend Framework 2 ciò che facevo con ZF1

CONVENTION

VS

CONFIGURATION

Page 64: Fare con Zend Framework 2 ciò che facevo con ZF1

Come sono fatti i controller?

64

Page 65: Fare con Zend Framework 2 ciò che facevo con ZF1

Controller Semplice in ZF2 <?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController

{

public function indexAction()

{

$timestamp = time();

return new ViewModel(array(

'timestamp' => $timestamp

));

}

}

Page 66: Fare con Zend Framework 2 ciò che facevo con ZF1

Action <?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController

{

public function indexAction()

{

$timestamp = time();

return new ViewModel(array(

'timestamp' => $timestamp

));

}

}

Page 67: Fare con Zend Framework 2 ciò che facevo con ZF1

Come interagisco con il model?

67

Page 68: Fare con Zend Framework 2 ciò che facevo con ZF1

Controller ZF1 […]

class IdraulicoController extends Zend_Controller_Action {

public function installaCaldaia () {

$operatore = new Operatore();

$esito = $operatore->installaCaldaia();

$this->view->esito =$esito;

}

Page 69: Fare con Zend Framework 2 ciò che facevo con ZF1

Scendiamo nel dettaglio […]

class IdraulicoController extends Zend_Controller_Action {

public function installaCaldaia () {

$operatore = new Operatore();

$esito = $operatore->installaCaldaia();

$this->view->esito =$esito;

}

Page 70: Fare con Zend Framework 2 ciò che facevo con ZF1

Com’è fatto questo oggetto? […]

Class Operatore {

public function __constructor () {

$this->caldaia = new Caldaia();

}

public function getCaldaia() {

return $this->caldaia;

}

public function installaCaldaia() {

// Fai qualcosa con $this->caldaia

}

}

Page 71: Fare con Zend Framework 2 ciò che facevo con ZF1

Dipendenza. Siamo vincolati! […]

Class Operatore {

public function __constructor () {

$this->caldaia = new Caldaia();

}

public function getCaldaia() {

return $this->caldaia;

}

public function installaCaldaia() {

// Fai qualcosa con $this->caldaia

}

}

Page 72: Fare con Zend Framework 2 ciò che facevo con ZF1

“IL PRINCIPIO DEL GARZONE”

Page 73: Fare con Zend Framework 2 ciò che facevo con ZF1

Siamo vincolati […]

Class Operatore {

public function __constructor (Caldaia $caldaia) {

$this->caldaia = $caldaia;

}

public function getCaldaia() {

return $this->caldaia;

}

public function installaCaldaia() {

// Fai qualcosa con $this->caldaia

}

}

Page 74: Fare con Zend Framework 2 ciò che facevo con ZF1

Siamo vincolati […]

Class Operatore {

public function __constructor (Caldaia $caldaia) {

$this->caldaia = $caldaia;

}

public function getCaldaia() {

return $this->caldaia;

}

public function installaCaldaia() {

// Fai qualcosa con $this->caldaia

}

}

Page 75: Fare con Zend Framework 2 ciò che facevo con ZF1

Test operatore […]

class OperatoreTest extends TestCase {

function testInstallaCaldaia() {

$caldaia = mockCaldaia();

$operatore = new Operatore($caldaia);

$esito = $operatore->installaCaldaia();

$this->assertTrue($esito);

}

}

Page 76: Fare con Zend Framework 2 ciò che facevo con ZF1

Da…

76

Page 77: Fare con Zend Framework 2 ciò che facevo con ZF1

A…

77

Page 78: Fare con Zend Framework 2 ciò che facevo con ZF1

INVERSIONE DI CONTROLLO

Page 79: Fare con Zend Framework 2 ciò che facevo con ZF1

Factory operatore […]

class OperatoreFactory {

public static function create ($nome) {

$caldaia = new Caldaia();

$operatore = new Operatore($caldaia);

return $operatore;

}

}

Page 80: Fare con Zend Framework 2 ciò che facevo con ZF1

Controller ZF1 […]

class IdraulicoController extends Zend_Controller_Action {

public function installaCaldaia () {

$I_operatore = OperatoreFactory::create();

$esito = $I_operatore->installaCaldaia();

$this->view->esito =$esito;

}

Page 81: Fare con Zend Framework 2 ciò che facevo con ZF1

ZF2 - Il Service Manager […]

class IdraulicoController extends AbstractActionController {

public function installaCaldaia () {

$operatore = $this->serviceLocator->get(‘operatore’);

$esito = $I_operatore->installaCaldaia();

return new ViewModel(‘operatore’ => $operatore,

‘esito’ => $esito);

}

Page 82: Fare con Zend Framework 2 ciò che facevo con ZF1

Riconsideriamo la configurazione return array(

...

'controllers' => array(

‘factories' => array(

'App\Controller\Idraulico' =>

'App\Controller\IdraulicoControllerFactory',

),),

‘service_manager’ =>

‘factories' => array(

‘operatore' => ‘MVA\Services\OperatoreFactory',

),

‘invokables' => array(

‘caldaia' => ‘MVA\Services\Caldaia',

),

‘aliases' => array(

‘attrezzi.martelloPneumatico' => ‘attrezzi.martello',

),

)

Page 83: Fare con Zend Framework 2 ciò che facevo con ZF1

Factories return array(

...

'controllers' => array(

‘factories' => array(

'App\Controller\Idraulico' =>

'App\Controller\IdraulicoControllerFactory',

),),

‘service_manager’ =>

‘factories' => array(

‘operatore' => ‘MVA\Services\OperatoreFactory',

),

‘invokables' => array(

‘caldaia' => ‘MVA\Services\Caldaia',

),

‘aliases' => array(

‘attrezzi.martelloPneumatico' => ‘attrezzi.martello',

),

)

Page 84: Fare con Zend Framework 2 ciò che facevo con ZF1

Invokables return array(

...

'controllers' => array(

‘factories' => array(

'App\Controller\Idraulico' =>

'App\Controller\IdraulicoControllerFactory',

),),

‘service_manager’ =>

‘factories' => array(

‘operatore' => ‘MVA\Services\OperatoreFactory',

),

‘invokables' => array(

‘caldaia' => ‘MVA\Services\Caldaia',

),

‘aliases' => array(

‘attrezzi.martelloPneumatico' => ‘attrezzi.martello',

),

)

Page 85: Fare con Zend Framework 2 ciò che facevo con ZF1

LAZY REGISTRY, ON STEROIDS

Page 86: Fare con Zend Framework 2 ciò che facevo con ZF1

Service Locator

Page 87: Fare con Zend Framework 2 ciò che facevo con ZF1

SE FATTO CON REGISTRY

Page 88: Fare con Zend Framework 2 ciò che facevo con ZF1

Service Locator

Page 89: Fare con Zend Framework 2 ciò che facevo con ZF1

Service Locator

Page 90: Fare con Zend Framework 2 ciò che facevo con ZF1

Uso di Alias return array(

...

'controllers' => array(

‘factories' => array(

'App\Controller\Idraulico' =>

'App\Controller\IdraulicoControllerFactory',

),

),

‘service_manager’ =>

‘invokables' => array(

‘attrezzi.martello' => 'App\Services\Martello',

‘attrezzi.martelloPneumatico‘ => 'App\Services\MartelloPneumatico',

),

)

Page 91: Fare con Zend Framework 2 ciò che facevo con ZF1

Uso di Alias return array(

...

'controllers' => array(

‘factories' => array(

'App\Controller\Idraulico' =>

'App\Controller\IdraulicoControllerFactory',

),

),

‘service_manager’ =>

[…]

‘invokables' => array(

‘attrezzi.martello' => 'App\Services\Martello',

‘attrezzi.supermartello' => 'App\Services\Martello',

),

‘aliases' => array(

‘attrezzi.martelloPneumatico' => ‘attrezzi.supermartello',

),

)

Page 92: Fare con Zend Framework 2 ciò che facevo con ZF1

I diversi service managers

Page 93: Fare con Zend Framework 2 ciò che facevo con ZF1

Diagramma service managers

Page 94: Fare con Zend Framework 2 ciò che facevo con ZF1

Peering

Page 95: Fare con Zend Framework 2 ciò che facevo con ZF1

Uso del Service Locator? […]

class Termostato implements ServiceLocatorAwareInterface {

[…]

public function getTemperatura() {

$sm = $this->getServiceLocator();

$sensore = $sm->get(‘Azienda\Model\TermoSensore');

return $sensore->getTemperatura();

}

public function setServiceLocator(ServiceLocatorInterface

$serviceLocator) {

$this->serviceLocator = $serviceLocator; }

public function getServiceLocator() {

return $this->serviceLocator; }

}

Page 96: Fare con Zend Framework 2 ciò che facevo con ZF1

Abuso del Service Locator […]

class Termostato implements ServiceLocatorAwareInterface {

[…]

public function getTemperatura() {

$sm = $this->getServiceLocator();

$sensore = $sm->get(‘Azienda\Model\TermoSensore');

return $sensore->getTemperatura();

}

public function setServiceLocator(ServiceLocatorInterface

$serviceLocator) {

$this->serviceLocator = $serviceLocator; }

public function getServiceLocator() {

return $this->serviceLocator; }

}

Page 97: Fare con Zend Framework 2 ciò che facevo con ZF1

ATTENZIONE!

Page 98: Fare con Zend Framework 2 ciò che facevo con ZF1

Abuso del Service Locator […]

class Termostato implements ServiceLocatorAwareInterface {

[…]

public function getTemperatura() {

$sm = $this->getServiceLocator();

$sensore = $sm->get(‘Azienda\Model\TermoSensore');

return $sensore->getTemperatura();

}

public function setServiceLocator(ServiceLocatorInterface

$serviceLocator) {

$this->serviceLocator = $serviceLocator; }

public function getServiceLocator() {

return $this->serviceLocator; }

}

Page 99: Fare con Zend Framework 2 ciò che facevo con ZF1

Factory per il Controller […]

Class IdraulicoControllerFactory implements

FactoryInterface {

public static function

createService(ServiceLocatorInterface $services) {

$sm = $services->getServiceLocator();

$operatore = $sm->get(‘Operatore');

return new IdraulicoController($operatore);

}

[…]

}

?>

Page 100: Fare con Zend Framework 2 ciò che facevo con ZF1

DEPENDENCY INJECTION

http://ocramius.github.com/blog/zend-framework-2-controllers-and-dependency-injection-with-zend-di/

Page 101: Fare con Zend Framework 2 ciò che facevo con ZF1

E per le funzioni di supporto?

101

Page 102: Fare con Zend Framework 2 ciò che facevo con ZF1

Scambio di messaggi class IdraulicoController {

public function installaCaldaiaAction() {

$operatore = $this->serviceLocator->get(‘operatore’);

$esito = $I_operatore->installaCaldaia();

$I_logger = new Logger();

$I_logger->log(‘Installazione Caldaia’);

return new ViewModel(‘operatore’ => $operatore,

‘esito’ => $esito);

}

}

Page 103: Fare con Zend Framework 2 ciò che facevo con ZF1

Mi trovo nel posto giusto? class IdraulicoController {

public function installaCaldaiaAction() {

$operatore = $this->serviceLocator->get(‘operatore’);

$esito = $I_operatore->installaCaldaia();

$I_logger = new Logger();

$I_logger->log(‘Installazione Caldaia’);

return new ViewModel(‘operatore’ => $operatore,

‘esito’ => $esito);

}

}

Page 104: Fare con Zend Framework 2 ciò che facevo con ZF1

Messaggio Diretto

Page 105: Fare con Zend Framework 2 ciò che facevo con ZF1

CROSS CUTTING CONCERNS

Page 106: Fare con Zend Framework 2 ciò che facevo con ZF1

Problema di estendibilità

$s_msg = ‘Installazione Caldaia’;

$I_logger = new Logger();

$I_logger->log($s_msg);

$I_mailer = new Mailer();

$I_mailer->mail($s_msg);

[…]

Page 107: Fare con Zend Framework 2 ciò che facevo con ZF1

Event Manager

Class Segretaria {

public function onFinitoIntervento() {

/* Occupati della Fatturazione */

}

}

Page 108: Fare con Zend Framework 2 ciò che facevo con ZF1

Event Manager Class IdraulicoFactory {

createService(ServiceLocatorInterface $serviceLocator) {

$idraulico = new Idraulico ();

$idraulico ->setEventManager(

$serviceLocator->get('eventManager')

);

$segretaria = $serviceLocator->get(‘segretaria');

$idraulico->getEventManager()->attach(

‘finitointervento',

array($segretaria, ‘onFinitoIntervento')

);

return $idraulico;

}

}

Page 109: Fare con Zend Framework 2 ciò che facevo con ZF1

Event Manager //nella classe che scatena l’evento...

class Idraulico {

public function installaCaldaia () {

/* Codice Installazione Caldaia */

$this->eventManager

->trigger(‘finitointervento‘,

$this,

array(‘azione’ => ‘Tutto OK!’)

);

}

}

Page 110: Fare con Zend Framework 2 ciò che facevo con ZF1

Event Manager

Page 111: Fare con Zend Framework 2 ciò che facevo con ZF1

OBSERVER

Page 112: Fare con Zend Framework 2 ciò che facevo con ZF1

Event Manager

Page 113: Fare con Zend Framework 2 ciò che facevo con ZF1

Come interagisco con il DB?

113

Page 114: Fare con Zend Framework 2 ciò che facevo con ZF1

ZEND\DB

Page 115: Fare con Zend Framework 2 ciò che facevo con ZF1

115

Page 116: Fare con Zend Framework 2 ciò che facevo con ZF1

Come uso controller plugin?

116

Page 117: Fare con Zend Framework 2 ciò che facevo con ZF1

Esempio con controller plugin <?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController

{

public function redirectAction()

{

$this->redirect()->toUrl(‘http://www.zfday.it’);

}

}

Page 118: Fare con Zend Framework 2 ciò che facevo con ZF1

Come recupero parametri?

118

Page 119: Fare con Zend Framework 2 ciò che facevo con ZF1

Factory per il Controller […]

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController

{

public function scriviNomeAction()

{

$nome = $this->getEvent()

->getRouteMatch()->getParam('slug');

return (‘nome’ => $nome);

}

}

Page 120: Fare con Zend Framework 2 ciò che facevo con ZF1

E se ho funzionalità ripetute?

120

Page 121: Fare con Zend Framework 2 ciò che facevo con ZF1

init() <?php

class IdraulicoController extends Zend_Controller_Action {

public function init () {

$this->view->azienda = $this->getParam(‘azienda’);

}

}

Page 122: Fare con Zend Framework 2 ciò che facevo con ZF1

Ma non ho ancora l’EM! […]

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController

{

public function __construct()

{

$this->azienda = $this->getEvent()

->getRouteMatch()->getParam(‘azienda');

}

}

Page 123: Fare con Zend Framework 2 ciò che facevo con ZF1

Sulla Dependency Injection… […]

// Sul costruttore

public function __construct($dipendenza) {

$this->dipendenza = $dipendenza;

}

// Con setters

Public function __construct() {

}

Public function setDipendenza() {

$this->dipendenza = $dipendenza;

}

Page 124: Fare con Zend Framework 2 ciò che facevo con ZF1

Agisco sul setter […]

use Zend\Mvc\Controller\AbstractActionController;

use Zend\View\Model\ViewModel;

class IdraulicoController extends AbstractActionController

{

public function setEventManager(EventManagerInterface $events) {

parent::setEventManager($events);

$controller = $this;

$events->attach('dispatch', function ($e) use ($controller) {

$this->name = $controller->params()->fromRoute(‘azienda',

‘Sconosciuta');

}

}}

Vedasi anche il post di M. W. O’Phinney: http://www.mwop.net/blog/2012-07-30-the-new-init.html

Page 125: Fare con Zend Framework 2 ciò che facevo con ZF1

Come funzionano le viste?

125

Page 126: Fare con Zend Framework 2 ciò che facevo con ZF1

Il layer di presentazione

Page 127: Fare con Zend Framework 2 ciò che facevo con ZF1

View //view index/index.phtml <div class="row">

<!-- Including header partial -->

<?php echo $this->partial('partials/header.phtml', array()); ?>

<!-- Stampiamo la data -->

<h1>Actual time is: <?php echo $this->timestamp;?></h1>

</div>

Page 128: Fare con Zend Framework 2 ciò che facevo con ZF1

View con helper //usando il view helper printData //view index/index.phtml

<div class="row">

<!-- Including header partial -->

<?php echo $this->partial('partials/header.phtml', array()); ?>

<!-- Stampiamo la data -->

<h1>Actual time is:

<?php echo $this->printData($this->timestamp);?>

</h1>

</div>

Page 129: Fare con Zend Framework 2 ciò che facevo con ZF1

Helper //Creando un viewHelper per formattare la data // Va registrato tra gli invokables del SM dei ViewHelpers

<?php

namespace Application\View\Helper;

class PrintData extends \Zend\View\Helper\AbstractHelper {

public function __invoke($timestamp) {

$date = new \DateTime();

$date->setTimestamp($timestamp);

$result = $date->format('d-m-Y H:i');

return $result;

}

}

Page 130: Fare con Zend Framework 2 ciò che facevo con ZF1

Come funzionano le form?

130

Page 131: Fare con Zend Framework 2 ciò che facevo con ZF1

Creando una form //Creiamo il file ContactForm dentro nostro modulo Application/src/Form

<?php

namespace Application\Form;

use Zend\Form\Element;

use Zend\Form\Form;

class ContactForm extends Form

{

public function __construct()

{

parent::__construct();

// …

}

//...

}

Page 132: Fare con Zend Framework 2 ciò che facevo con ZF1

Form: aggiungiamo i campi public function init() {

$this->setName('contact');

$this->add(array(

'name' => ‘emailMittente',

'type' => 'Zend\Form\Element\Text',

'options' => array(

'label' => 'From:',

),

)

$this->add(array(

'name' => 'Send',

'type' => 'Zend\Form\Element\Submit',

'attributes' => array(

'value' => 'Send',

),); //...

}

}

Page 133: Fare con Zend Framework 2 ciò che facevo con ZF1

La Form

Form

Page 134: Fare con Zend Framework 2 ciò che facevo con ZF1

Gli InputFilter

Page 135: Fare con Zend Framework 2 ciò che facevo con ZF1

Validation: inputFilter //creiamo l'imput filter contactFilter.php dentro Application/src/Form

<?php

namespace Application\Form;

use Zend\InputFilter\InputFilter;

use Zend\Validator\Hostname as HostnameValidator;

class ContactFilter extends InputFilter

{

public function __construct()

{

//aggiungiamo i filtri

}

}

Page 136: Fare con Zend Framework 2 ciò che facevo con ZF1

InputFilter: filter & validation //Esempio filtering(trim) + email validation with custom message

$this->add(array(

'name' => ‘emailMittente',

'required' => true,

'filters' => array(

array('name' => 'StringTrim'),

),

'validators' => array(

array(

'name' => 'EmailAddress',

'options' => array(

'messages' => array(

\Zend\Validator\EmailAddress::INVALID =>

'L\'indirizzo email inserito non è valido.'),

)

)

)

));

Page 137: Fare con Zend Framework 2 ciò che facevo con ZF1

Controller: Usando la form namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Application\Form\Contact;

use Application\Form\ContactFilter;

class IndexController extends AbstractActionController

{

public function contactAction()

{

$form = new Contact();

$filter = new ContactFilter();

$form->setInputFilter($filter);

return new ViewModel(array(

'form' => $form

);

}

}

Page 138: Fare con Zend Framework 2 ciò che facevo con ZF1

View: Usando la form <?php

$form = $this->form;

$form->setAttribute('action', $this->url('contact'));

$form->prepare();

echo $this->form()->openTag($form); ?>

<dl class="contact_form">

<dt><?php echo $this->formLabel($form->get('from')); ?></dt>

<dd><?php

echo $this->formInput($form->get('from'));

echo $this->formElementErrors($form->get('from'));

?></dd>

<!-- ... -->

</dl>

<?php echo $this->form()->closeTag($form) ?>;

Page 139: Fare con Zend Framework 2 ciò che facevo con ZF1

Una form più filtri

Page 140: Fare con Zend Framework 2 ciò che facevo con ZF1

Come posso proseguire?

140

Page 141: Fare con Zend Framework 2 ciò che facevo con ZF1

Per Approfondire

141

Page 142: Fare con Zend Framework 2 ciò che facevo con ZF1

Per Approfondire

142

Page 143: Fare con Zend Framework 2 ciò che facevo con ZF1

Sporcati le mani: https://packages.zendframework.com/docs/latest/manual/en/user-guide/overview.html

143

Page 144: Fare con Zend Framework 2 ciò che facevo con ZF1

Segui i migliori eventi

144

http://www.phpday.it

Page 145: Fare con Zend Framework 2 ciò che facevo con ZF1

In sintesi 1. Maggior enfasi sul riuso. Tenere a mente

che ci sono i Moduli 2. Su ZF2 si segue maggiormente un

approccio orientato alla configurazione piuttosto che convenzione

3. Lo strumento cerca di favorire il disaccoppiamento (EventManager) e l’inversione di controllo (ServiceManager, DI)

145

Page 146: Fare con Zend Framework 2 ciò che facevo con ZF1

Grazie per l’attenzione

Stefano Maraspin @maraspin [email protected]

Page 147: Fare con Zend Framework 2 ciò che facevo con ZF1

DOMANDE?

Page 148: Fare con Zend Framework 2 ciò che facevo con ZF1

Photo Credits • http://www.flickr.com/photos/cclark395/7671665642/ • http://www.flickr.com/photos/thompsonrivers/8072087088/ • http://www.flickr.com/photos/ter-burg/5807937726/ • http://www.flickr.com/photos/cimmyt/7798631622/ • http://www.flickr.com/photos/reckless_sniper/6568298617/ • http://www.flickr.com/photos/fil/144232588/ • http://www.flickr.com/photos/ponchopenguin/3262049873/ • http://www.flickr.com/photos/hugosimmelink/1791812548/ • http://www.flickr.com/photos/calsidyrose/4925267732/ • http://www.flickr.com/photos/29233640@N07/8412347937/ • http://www.flickr.com/photos/stungeye/2774997317/ • http://www.flickr.com/photos/urbanwoodswalker/4375401057/ • http://www.flickr.com/photos/adelaide_archivist/3262863212/ • http://www.flickr.com/photos/syslfrog/172945973/ • http://www.flickr.com/photos/tognum/6279595321/ • http://www.flickr.com/photos/dominichargreaves/2825624738/ • http://www.flickr.com/photos/lstcaress/502606063/ • http://www.flickr.com/photos/a-g/2128462119/ • http://www.flickr.com/photos/see-through-the-eye-of-g/4087838437/

148

Page 149: Fare con Zend Framework 2 ciò che facevo con ZF1

Stefano Maraspin @maraspin [email protected]