Levate l'ancora! Rotte senza problemi con ZF2
-
Upload
diego-drigani -
Category
Technology
-
view
1.888 -
download
0
description
Transcript of Levate l'ancora! Rotte senza problemi con ZF2
Levate l'ancora! Rotte senza problemi con ZF2
Zend Framework DAY, Milano - Italia 01-02-2013
Diego Drigani
@drigani
http://www.mvassociati.it/
http://friuli.grusp.org/
COS’È IL ROUTING?
Partiamo da una richiesta
http://sales.it/products/smartphones
Principio fondamentale di routing • Matching di una richiesta ed estrazione
dei parametri • Assembling di nuove richieste
Under the hood namespace Zend\Mvc\Router;
use Zend\Stdlib\RequestInterface as Request;
interface RouteInterface
{
public static function factory($options = array());
public function match(Request $request);
public function assemble(
array $params = array(),
array $options = array());
}
PERCHÈ IL ROUTING È IMPORTANTE?
USER FRIENDLY URL
SEO FRIENDLY URL
MAGGIOR SICUREZZA
RESTFUL SERVICES API
TIPI DI ROTTE
http://www.zfday.it/about-us
16
Richiesta http://www.zfday.it/about-us
Literal route • Il più semplice • Fa il matching/assembling letterale di una
stringa • Non fa matching di alcun parametro
17
Literal route (esempio) array(
'about' => array(
'type' => 'Literal',
'options' => array(
'route' => '/about-us',
'defaults' => array(
'controller' => 'Pages',
'action' => 'about-us',
)
)
)
)
http://www.hubme.in/get/cfps.atom
http://www.hubme.in/get/events.rss
19
Richiesta
http://www.hubme.in/get/cfps.atom http://www.hubme.in/get/events.rss
Regex route • Il tipo di rotta parameter-matching più
veloce • Il matching basato su regexp • Fa l’assembling sulla base di un
replacement pattern
20
Regex route (esempio) array(
'get' => array(
'type' => 'Regex',
'options' => array(
'regex'=>
/* Definizione di Named Sub patterns, ad es:
?<type> e ?<format> */
/get/(?<type>(events|cfps))(\.(?<format>(atom|rss)))?',
'defaults' => array(
'controller' => 'Api',
'action' => 'get',
),
//Usato al momento dell’assemble
'spec' => '/get/%type%.%format%',
)
)
)
http://sale.it/catalog?brand=epson&priceto=200
22
Richiesta http://sale.it/catalog?brand=epson&priceto=200
Query route • Consente di specificare e catturare
parametri della query string • L’idea è che venga usata come
child_route di un’altra rotta.
23
Query route (esempio)
array(
//...
'catalog_query' => array(
'type' => 'Query'
)
)
http://sale.it/catalog
25
http://sale.it/catalog/electronics
Richiesta
http://sale.it/catalog/electronics/smartphones
http://sale.it/catalog http://sale.it/catalog/electronics http://sale.it/catalog/electronics/smartphones
Segment route • Il tipo più flessibile • Matching molto veloce, giacchè i segment
patterns sono internamente convertiti in regexp
• Fornisce il matching dei parametri basato su delimeters e constraints
• Consente segmenti opzionali (letterali e segmenti)
26
Segment route (esempio) array(
'catalog' => array(
'type' => 'Segment',
'options' => array(
'route' => '/catalog[/:category[/:subcategory]]',
'constraints' => array(
‘category‘ => '[a-zA-Z][a-zA-Z0-9._-]*',
‘subcategory' => '[a-zA-Z][a-zA-Z0-9._-]*',
),
'defaults' => array(
'controller' => 'Catalog',
'action' => 'index',
)
)
)
)
Struttura segment patterns • I segmenti opzionali
– Sono indicati tra parentesi quadre – Possono essere annidati – Possono contenere letterali e parametri
• Il delimitatore di default per i parametri è la barra, ma può essere modificato con parentesi graffe
28
Segment patterns (esempio) • /events[/page-:id]
– Matches: • /events • /events/page-1
29
Segment patterns (esempio) • /events/[page-:id]
– Matches: • /events/ • /events/page-1
30
Combinando alcune rotte array(
'catalog' => array(
'type' => 'Literal',
'options' => array(
'route' => '/catalog',
'defaults' => array(
'controller' => 'Catalog',
'action' => 'index',
)
),
'may_terminate' => true,
'child_routes' => array(
'category' => array(
'type' => 'Segment',
'options' => array(
'route' => '/:category',
//...
)
)
) …
TIPI AVANZATI DI ROTTE
Matching fuori dal path • Hostname route
– :user.users.cpanel.it • diego.users.cpanel.it
• Scheme route – http, https, ...
• Method route – GET, POST, PUT, ...
33
ROUTING NELLE APPLICAZIONI
//module.config.php
return array(
'router' => array(
'routes' => array(
// ...
)
)
);
Definizione delle rotte
I parametri dal controller
class ZfdayController extends AbstractActionController
{
public function indexAction()
{
$id = $this->params('id'/*, null */);
}
}
Redirect
class ZfdayController extends AbstractActionController
{
public function indexAction()
{
$this->redirect()->toRoute(
'routeName',
array(), // Params
array() // Options
);
}
}
Assembling URLs nel controller class ZfdayController extends AbstractActionController
{
public function indexAction()
{
$url = $this->url()->fromRoute(
'routeName',
array(), // Params
array() // Options
);
$this->redirect()->toUrl($url . '#anchorName');
}
}
Assembling URLs nella view
<a href="<?php echo $this->url(
'routeName',
array(), // Params
array() // Options
);?>">Some Link</a>
APPLICAZIONI CLI E ROUTING
Introduzione console routing • ZF2 ha una integrazione nativa del MVC
con la console • Permette di individuare controller e action
da eseguire a partire da un comando della console
• Le action sono eseguite e il risultato è mostrato nella console
41
Boostrapping ZF2 Create file: bin/ecommerce-console
#!/usr/bin/php
<?php
include __DIR__.'/../public/index.php';
CLI: controller esempio
class ProductsController extends AbstractActionController {
public function importAction() {
$request = $this->getRequest();
if (!$request instanceof Zend\Console\Request){
throw new \RuntimeException('only from console!');
}
//do products import
return 'Import done!';
}
public function updateAction() {
//do products update prices and stocks
return 'Update done!';
}
}
Definizione: console routing array(
'router' => array(
'routes' => array(
// HTTP routes are defined here
)
),
'console' => array(
'router' => array(
'routes' => array(
// Console routes go here
)
)
)
)
CLI Routing: esempio array(
'console' => array(
'router' => array(
'routes' => array(
'command_import' => array(
'type' => 'simple',
'options' => array(
'route' => 'import',
'defaults' => array(
'controller' => 'Products',
'action' => 'import',
)
)
)
)
)
)
)
CLI Routing: esempio
Conclusioni • Il Routing è stato scritto da zero per ZF2 • E’ abbastanza simile a ZF1, ma i
meccanismi interni sono più coerenti, performanti, e spesso più semplici.
• ZF2 ha una integrazione nativa del MVC con la console
47
DOMANDE?
Grazie per l’attenzione!
Diego Drigani @drigani [email protected]
Photo Credits • http://www.flickr.com/photos/calsidyrose/4925267732/ • http://www.flickr.com/photos/wili/2692420732/ • http://www.flickr.com/photos/theseanster93/5027792986/ • http://www.flickr.com/photos/mcbarnicle/7291518436/ • http://www.flickr.com/photos/arthurfa varo/8383257961/ • http://www.flickr.com/photos/alt-n-anela/6186835140 • http://www.flickr.com/photos/neilsingapore/4236445041/ • http://www.flickr.com/photos/thecolormarlee/4961780746/
50
Diego Drigani @drigani [email protected]