SlideShare uma empresa Scribd logo
1 de 67
Baixar para ler offline
Os Pilares do Zend Framework 2
Construindo Aplicações Realmente Modulares
@Pauloelr
Sobre Mim
@Pauloelr
Oi, Meu nome é Paulo Eduardo
Eu não estou usando sintetizador de voz
Objetivos
Um Pouco de História
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
2007 - Versão 1.0
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
2007 - Versão 1.0
2012 - Versão 2.0
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
2007 - Versão 1.0
2012 - Versão 2.0
2015 - Versão 2.5
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
2007 - Versão 1.0
2012 - Versão 2.0
2015 - Versão 2.5
2016 - Versão 3.0
Zend Framework
Mantenedor: Zend Technologies
Líder de Projeto: Matthew Weier O’Phinney
Versão Atual: 2.5.3
Licença: BSD
2005 - Início do Projeto
2007 - Versão 1.0
2012 - Versão 2.0
Performance:
Curva de Aprendizado:
Facilidade de Uso:
Suporte da Comunidade:
Qualidade da Documentação:
Qualidade do Código:
Cobertura de Testes
Compatibilidade
2015 - Versão 2.5
2016 - Versão 3.0
Previsão de Lançamento em 2016
Suporte ao PHP 5.6+
Com Suporte à Namespaces (PSR-4)
Framework FullStack como Meta-Repositório
Minimas Dependencias Entre Componentes
Aplicações Baseadas em Módulos ou Middlewares
Melhorias Técnicas Implementadas
Muito Mais Leve e Rápido
Suporte Oficial ao PHPUnit
Ausência de ORM (Somente TableGateway)
Suporte a Doctrine, Propel e Outros (Módulos)
Baixa Quebra de Compatibilidade com Versão 2.x
Zend Framework 3
Primeira Versão Estável Lançada em 2012
Suporte ao PHP 5.3.3+ (5.5+ Após 2.5.0)
Com Suporte à Namespaces (Padrão PHP)
Suporte ao Composer (Inclusive para Componentes)
Médias Dependências Entre Componentes
Aplicações Baseadas em Módulos
Melhorias Técnicas Implementadas
Menos Pesado (Ainda um Pouco)
Suporte Oficial ao PHPUnit
Ausência de ORM (Somente TableGateway)
Suporte a Doctrine, Propel e Outros (Módulos)
Alta Quebra de Compatibilidade com Versão 1.x
Zend Framework 2
Primeira Versão Estável Lançada em 2007
Suporte ao PHP 5.1.4+ (5.2.3+ Recomendada)
Sem Suporte à Namespaces (Uso Alternativo)
Sem Suporte a Composer (Instalação Manual)
Componentes Altamento Acoplados
Ausência de Módulos
Uso de Técnicas Consideradas Antipatterns
Bastante Pesado
Sem Suporte Oficial a Testes Unitários
Componente de ORM Próprio
Sem Suporte a Outros ORM’s
Retrocompatbilidade com Versões Anteriores
Zend Framework 1
Os Pilares do Zend Framework 2
Module Manager
O Que são Módulos?
Our ultimate goal is extensible programming. By this,
we mean the construction of hierarchies of modules,
each module adding new functionality to the system
Niklaus Wirth
Características do Module Manager
Gerencia
os Módulos
Mescla as
Configurações
Gerencia as
Dependências
Extensibilidade
de Módulos
Sobrescrita
de Módulos
Autoload de Modules
<?php
return [
'modules' => [
'Sample'
],
'module_listener_options' => [
'config_glob_paths' => [
'config/autoload/{,*.}{global,local}.php'
],
'module_paths' => [
'./module',
'./vendor'
]
]
];
config/application.config.php
Formatos: .phar, .phar.gz, .phar.bz2, .phar.tar, .phar.tar.gz,
.phar.tar.bz2, .phar.zip, .tar, .tar.gz, .tar.bz2, e .zip.
<?php
chdir(dirname(__DIR__));
/** @noinspection PhpIncludeInspection */
require 'vendor/autoload.php';
/** @noinspection PhpIncludeInspection */
ZendMvcApplication::init(require 'config/application.config.php')->run();
index.php
Módulos no Zend Framework 2
<?php
namespace Sample;
class Module{}
Module.php
Módulos no Zend Framework 2
<?php
namespace Sample;
class Module
{
public function getConfig()
{
return include __DIR__ . ‘/../config/module.config.php’;
}
}
Module.php
Módulos no Zend Framework 2
<?php
namespace Sample;
use ZendStdlibArrayUtils;
class Module
{
public function getConfig()
{
$config = [];
$configFiles = [
__DIR__ . ‘/../config/module.config.php’,
__DIR__ . ‘/../config/service.config.php’,
];
foreach ($configFiles as $configFile) {
$config = ArrayUtils::merge($config, include $configFile);
}
return $config;
}
}
Module.php
ModuleLoaderListener
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
ConfigListener
getConfig()
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
InitTrigger
init()
ConfigListener
getConfig()
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
InitTrigger
init()
ConfigListener
getConfig()
LocatorRegistrationListener
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
InitTrigger
init()
ConfigListener
getConfig()
LocatorRegistrationListener
ModuleResolverListener
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
InitTrigger
init()
ConfigListener
getConfig()
LocatorRegistrationListener
ModuleResolverListener
OnBootstrapListener
onBootstrap()
ModuleLoaderListener
AutoloaderListener
getAutooaderConfig()
ModuleDependencyCheckerListener
getModuleDependencies()
InitTrigger
init()
ConfigListener
getConfig()
LocatorRegistrationListener
ModuleResolverListener
OnBootstrapListener
onBootstrap()
ServiceListener
getServiceConfig()
Configuration Merge
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘type’ => ‘Literal’,
‘options’ => [
‘route’ => ‘/user’,
‘defaults’ => [
‘__NAMESPACE__’ => ‘SampleController’,
‘controller’ => ‘User’,
‘action’ => ‘index’,
],],],],],];
Módulo de Terceiro (ThirdUser)
Configuration Merge
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘type’ => ‘Literal’,
‘options’ => [
‘route’ => ‘/user’,
‘defaults’ => [
‘__NAMESPACE__’ => ‘SampleController’,
‘controller’ => ‘User’,
‘action’ => ‘index’,
],],],],],];
Módulo de Terceiro (ThirdUser)
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘options’ => [
‘route’ => ‘admin/user’,
],
],
],
],
];
Meu Módulo (MyUser)
Configuration Merge
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘type’ => ‘Literal’,
‘options’ => [
‘route’ => ‘/user’,
‘defaults’ => [
‘__NAMESPACE__’ => ‘SampleController’,
‘controller’ => ‘User’,
‘action’ => ‘index’,
],],],],],];
Módulo de Terceiro (ThirdUser)
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘options’ => [
‘route’ => ‘admin/user’,
],
],
],
],
];
Meu Módulo (MyUser)
<?php
return [
‘modules’ => [
‘ThirdUser’,
‘MyUser’
],
];
config/application.config.php
Configuration Merge
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘type’ => ‘Literal’,
‘options’ => [
‘route’ => ‘/user’,
‘defaults’ => [
‘__NAMESPACE__’ => ‘SampleController’,
‘controller’ => ‘User’,
‘action’ => ‘index’,
],],],],],];
Módulo de Terceiro (ThirdUser)
<?php
return [
‘router’ => [
‘routes’ => [
‘user’ => [
‘options’ => [
‘route’ => ‘admin/user’,
],
],
],
],
];
Meu Módulo (MyUser)
<?php
return [
'router' => [
'routes' => [
'user' => [
'type' => 'Literal',
'options' => [
'route' => 'admin/user',
'defaults' => [
'__NAMESPACE__' => 'SampleController',
'controller' => 'User',
'action' => 'index',
],
],
],
],
],
];
Resultado
<?php
return [
‘modules’ => [
‘ThirdUser’,
‘MyUser’
],
];
config/application.config.php
DoctrineORMModule
ZfcUser
TwbBundle
ZfcRbac ZfcTwig
http://modules.zendframework.com/
Service Manager
O Que são Serviços?
A mechanism to enable access to one or more capabilities,
where the access is provided using a prescribed interface
and is exercised consistent with constraints and policies
as specified by the service description.
Organization for the Advancement of Structured Information Standards (OASIS)
Características do Service Manager
Gerencia
os Serviços
Injeção de
Dependências
Inversão do
Controle
Serviços
Modulares
Compartilhados
ou
Independentes
Serviços no Zend Framework 2
<?php
use SampleUserFormUserFieldset;
use SampleUserFormUserFieldsetFactory;
use SampleUserFormUserForm;
use SampleUserFormUserFormFactory;
use SampleUserMapperUserMapperFactory;
use SampleUserControllerUserControllerFactory;
return [
'service_manager'=>[
'factories' => [
'SampleUserMapperUserMapper' => UserMapperFactory::class,
],
],
'form_elements'=>[
'factories' => [
UserFieldset::class => UserFieldsetFactory::class,
UserForm::class => UserFormFactory::class,
],
],
'controllers'=>[
'factories' => [
'SampleUserControllerUser' => UserControllerFactory::class,
],
],
];
Serviços no Zend Framework 2
<?php
namespace SampleUserForm;
use DoctrineCommonPersistenceObjectManager;
use DoctrineORMEntityManager;
use DoctrineModuleStdlibHydratorDoctrineObject as DoctrineHydrator;
use SampleUserEntityUser;
use ZendFormFormElementManager;
use ZendServiceManagerFactoryInterface;
use ZendServiceManagerServiceLocatorInterface;
class UserFieldsetFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $formManager)
{
/** @var $formManager FormElementManager */
$serviceManager = $formManager->getServiceLocator();
/** @var $objectManager ObjectManager */
$objectManager = $serviceManager->get(EntityManager::class);
$userFieldset = new UserFieldset();
$userHydrator = new DoctrineHydrator($objectManager, User::class);
$userFieldset->setHydrator($userHydrator);
$userFieldset->setObject(new User());
return $userFieldset;
}
}
Tipos de Serviços
Plugin Manager Config Key Interface Module Method
ZendMvcControllerControllerManager controllers ControllerProviderInterface getControllerConfig
ZendMvcControllerPluginManager controller_plugins ControllerPluginProviderInterface getControllerPluginConfig
ZendFilterFilterPluginManager filters FilterProviderInterface getFilterConfig
ZendFormFormElementManager form_elements FormElementProviderInterface getFormElementConfig
ZendStdlibHydratorHydratorPluginManager hydrators HydratorProviderInterface getHydratorConfig
ZendInputFilterInputFilterPluginManager input_filters InputFilterProviderInterface getInputFilterConfig
ZendMvcRouterRoutePluginManager route_manager RouteProviderInterface getRouteConfig
ZendSerializerAdapterPluginManager serializers SerializerProviderInterface getSerializerConfig
ZendServiceManagerServiceManager service_manager ServiceProviderInterface getServiceConfig
ZendValidatorValidatorPluginManager validators ValidatorProviderInterface getValidatorConfig
ZendViewHelperPluginManager view_helpers ViewHelperProviderInterface getViewHelperConfig
ZendLogProcessorPluginManager log_processors LogProcessorProviderInterface getLogProcessorConfig
ZendLogWriterPluginManager log_writers LogWriterProviderInterface getLogWriterConfig
services, invokables, factories, abstract_factories
Event Manager
O Que são Eventos?
An event is an action or occurrence recognised
by software that may be handled by the software
Wikipedia
Características do Event Manager
Event Driven
Architecture
Evento MVC
(“Principal“)
Integração
entre Módulos
Eventos
Personalizados
Compartilhados
ou
Independentes
Eventos no Zend Framework 2
<?php
use ZendEventManagerEventManager;
use ZendEventManagerEventManagerAwareInterface;
use ZendEventManagerEventManagerInterface;
class Example implements EventManagerAwareInterface
{
protected $events;
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_class($this)
));
$this->events = $events;
}
public function getEventManager()
{
if (!$this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
public function doIt($foo, $baz)
{
$params = compact(‘foo’, ‘baz’);
$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}
Eventos no Zend Framework 2
<?php
use ZendEventManagerEventManager;
use ZendEventManagerEventManagerAwareInterface;
use ZendEventManagerEventManagerInterface;
class Example implements EventManagerAwareInterface
{
protected $events;
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_class($this)
));
$this->events = $events;
}
public function getEventManager()
{
if (!$this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
public function doIt($foo, $baz)
{
$params = compact(‘foo’, ‘baz’);
$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}
<?php
$example = new Example();
$example->getEventManager()->attach('doIt', function($e) {
/** @var $e ZendEventManagerEventInterface */
$event = $e->getName();
$target = get_class($e->getTarget()); // "Example"
$params = $e->getParams();
printf(
'Handled event "%s" on target "%s", with parameters %s',
$event,
$target,
json_encode($params)
);
});
$example->doIt('bar', 'bat');
Eventos no Zend Framework 2
<?php
use ZendEventManagerEventManager;
use ZendEventManagerEventManagerAwareInterface;
use ZendEventManagerEventManagerInterface;
class Example implements EventManagerAwareInterface
{
protected $events;
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_class($this)
));
$this->events = $events;
}
public function getEventManager()
{
if (!$this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
public function doIt($foo, $baz)
{
$params = compact(‘foo’, ‘baz’);
$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}
<?php
use ZendEventManagerSharedEventManager;
$sharedEvents = new SharedEventManager();
$sharedEvents->attach(‘Example’, ‘do’, function ($e) {
/** @var $e ZendEventManagerEventInterface */
$event = $e->getName();
$target = get_class($e->getTarget()); // “Example”
$params = $e->getParams();
printf(
‘Handled event “%s” on target “%s”, with parameters %s’,
$event,
$target,
json_encode($params)
);
});
$example = new Example();
$example->getEventManager()->setSharedManager($sharedEvents);
$example->doIt(‘bar’, ‘bat’);
Exemplos de Eventos
<?php
namespace SampleUserService;
use ZendEventManagerEventManager;
use ZendEventManagerEventManagerAwareInterface;
use ZendEventManagerEventManagerInterface;
class UserService implements EventManagerAwareInterface
{
protected $eventManager;
public function addUser($user)
{
// Logic to Add User
$this->getEventManager()->trigger('addUser', null, array('user' => $user));
}
public function setEventManager(EventManagerInterface $eventManager)
{
$eventManager->addIdentifiers(array(
get_called_class()
));
$this->eventManager = $eventManager;
}
public function getEventManager()
{
if (null === $this->eventManager) {
$this->setEventManager(new EventManager());
}
return $this->eventManager;
}
}
Exemplos de Eventos
<?php
namespace SampleUser;
use ZendMvcMvcEvent;
class Module
{
public function onBootstrap(MvcEvent $event)
{
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$sharedEventManager->attach('SampleUserServiceUserService', 'addUser', function($e) {
//Logic to Send User
}, 100);
}
}
Exemplos de Eventos
<?php
namespace SampleUser;
use ZendMvcMvcEvent;
class Module
{
public function onBootstrap(MvcEvent $event)
{
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$sharedEventManager->attach('SampleUserServiceUserService', 'addUser', function($e) {
//Logic to Send Mail
}, 100);
}
}
<?php
namespace SampleUser;
use ZendMvcMvcEvent;
class Module
{
public function onBootstrap(MvcEvent $event)
{
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$emailListener = new EmailListener();
$emailListener->attachShared($sharedEventManager);
}
}
Exemplos de Eventos
<?php
namespace SampleUserListener;
use ZendEventManagerSharedEventManagerInterface;
use ZendEventManagerSharedListenerAggregateInterface;
use ZendMvcMvcEvent;
class EmailListener implements SharedListenerAggregateInterface
{
protected $listeners = [];
public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100)
{
$this->listeners[] = $eventManager->attach(
‘SampleUserServiceUserService’,
‘addUser’,
[$this, 'onAddUser'],
$priority
);
}
public function detachShared(SharedEventManagerInterface $eventManager)
{
foreach ($this->listeners as $index => $listener) {
if ($eventManager->detach(‘SampleUserServiceUserService’, $listener)) {
unset($this->listeners[$index]);
}
}
}
public function onAddUser($event)
{
//Logic to Send User
}
}
Evento MVC
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_DISPATCH
dispatch
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_DISPATCH
dispatch
MvcEvent::EVENT_DISPATCH_ERROR
dispatch.error
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_DISPATCH
dispatch
MvcEvent::EVENT_RENDER
renderer
MvcEvent::EVENT_DISPATCH_ERROR
dispatch.error
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_DISPATCH
dispatch
MvcEvent::EVENT_RENDER
renderer
MvcEvent::EVENT_DISPATCH_ERROR
dispatch.error
MvcEvent::EVENT_RENDER_ERROR
render.error
MvcEvent::EVENT_BOOTSTRAP
bootstrap
MvcEvent::EVENT_ROUTE
route
MvcEvent::EVENT_DISPATCH
dispatch
MvcEvent::EVENT_RENDER
renderer
MvcEvent::EVENT_DISPATCH_ERROR
dispatch.error
MvcEvent::EVENT_RENDER_ERROR
render.error
MvcEvent::EVENT_FINISH
finish
Evento MVC
<?php
namespace PsycoPantheonCoreLayoutListener;
use ZendEventManagerSharedEventManagerInterface;
use ZendEventManagerSharedListenerAggregateInterface;
use ZendMvcMvcEvent;
class CrazyListener implements SharedListenerAggregateInterface
{
protected $listeners = [];
public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100)
{
$this->listeners[] = $eventManager->attach(
'application', MvcEvent::EVENT_DISPATCH, [$this, 'doSomethingCrazy'], $priority
);
}
public function detachShared(SharedEventManagerInterface $eventManager){//...}
public function doSomethingCrazy(MvcEvent $mvcEvent){//Do Something Crazy}
}
Evento MVC
<?php
namespace PsycoPantheonCoreLayoutListener;
use ZendEventManagerSharedEventManagerInterface;
use ZendEventManagerSharedListenerAggregateInterface;
use ZendMvcMvcEvent;
class CrazyListener implements SharedListenerAggregateInterface
{
protected $listeners = [];
public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100)
{
$this->listeners[] = $eventManager->attach(
'application', MvcEvent::EVENT_DISPATCH, [$this, 'doSomethingCrazy'], $priority
);
}
public function detachShared(SharedEventManagerInterface $eventManager){//...}
public function doSomethingCrazy(MvcEvent $mvcEvent){//Do Something Crazy}
}
<?php
namespace SampleUser;
use ZendMvcMvcEvent;
class Module
{
public function onBootstrap(MvcEvent $event)
{
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$crazyListener = new CrazyListener();
$crazyListener->attachShared($sharedEventManager);
}
}
Novidades
Componentes Modularizados
Middlewares
Conclusão
Dúvidas?
Obrigado a Todos
Obrigado a Todos
Agradecimentos
PHPSP

Mais conteúdo relacionado

Destaque

Atividades fim de semana 23 e 24 junho
Atividades fim de semana  23 e 24 junhoAtividades fim de semana  23 e 24 junho
Atividades fim de semana 23 e 24 junhoSofia Cabral
 
Só a presença de jesus
Só a presença de jesusSó a presença de jesus
Só a presença de jesusbarbara araujo
 
R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15Russ LaChanse, MBA
 
Ensayo final
Ensayo finalEnsayo final
Ensayo finalRay Mor
 
Orquestrando Aplicações PHP com Symfony
Orquestrando Aplicações PHP com SymfonyOrquestrando Aplicações PHP com Symfony
Orquestrando Aplicações PHP com SymfonyFlávio Lisboa
 
Beyond PSR-7: The magical middleware tour
Beyond PSR-7: The magical middleware tourBeyond PSR-7: The magical middleware tour
Beyond PSR-7: The magical middleware tourmarco perone
 
ReferenceLetterSparebank1
ReferenceLetterSparebank1ReferenceLetterSparebank1
ReferenceLetterSparebank1henripenri
 
TDC 2015 - Wearables no IoT (PT-BR)
TDC 2015 - Wearables no IoT (PT-BR)TDC 2015 - Wearables no IoT (PT-BR)
TDC 2015 - Wearables no IoT (PT-BR)Matheus Marabesi
 
TDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streamsTDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streamsMatheus Marabesi
 

Destaque (11)

Atividades fim de semana 23 e 24 junho
Atividades fim de semana  23 e 24 junhoAtividades fim de semana  23 e 24 junho
Atividades fim de semana 23 e 24 junho
 
Só a presença de jesus
Só a presença de jesusSó a presença de jesus
Só a presença de jesus
 
R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15
 
Ensayo final
Ensayo finalEnsayo final
Ensayo final
 
certificate
certificatecertificate
certificate
 
Using ICT in primary school.
Using ICT in primary school. Using ICT in primary school.
Using ICT in primary school.
 
Orquestrando Aplicações PHP com Symfony
Orquestrando Aplicações PHP com SymfonyOrquestrando Aplicações PHP com Symfony
Orquestrando Aplicações PHP com Symfony
 
Beyond PSR-7: The magical middleware tour
Beyond PSR-7: The magical middleware tourBeyond PSR-7: The magical middleware tour
Beyond PSR-7: The magical middleware tour
 
ReferenceLetterSparebank1
ReferenceLetterSparebank1ReferenceLetterSparebank1
ReferenceLetterSparebank1
 
TDC 2015 - Wearables no IoT (PT-BR)
TDC 2015 - Wearables no IoT (PT-BR)TDC 2015 - Wearables no IoT (PT-BR)
TDC 2015 - Wearables no IoT (PT-BR)
 
TDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streamsTDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streams
 

Semelhante a Pilares do Zend Framework 2

Semelhante a Pilares do Zend Framework 2 (20)

Demo
DemoDemo
Demo
 
first pitch
first pitchfirst pitch
first pitch
 
werwr
werwrwerwr
werwr
 
sdfsdf
sdfsdfsdfsdf
sdfsdf
 
college
collegecollege
college
 
first pitch
first pitchfirst pitch
first pitch
 
Greenathan
GreenathanGreenathan
Greenathan
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 
first pitch
first pitchfirst pitch
first pitch
 
organic
organicorganic
organic
 
first pitch
first pitchfirst pitch
first pitch
 
latest slide
latest slidelatest slide
latest slide
 
345
345345
345
 
before upload
before uploadbefore upload
before upload
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 
sadasd
sadasdsadasd
sadasd
 
asdf
asdfasdf
asdf
 
for test7
for test7for test7
for test7
 
latest slide
latest slidelatest slide
latest slide
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 

Último

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Último (20)

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Pilares do Zend Framework 2

  • 1. Os Pilares do Zend Framework 2 Construindo Aplicações Realmente Modulares @Pauloelr
  • 2. Sobre Mim @Pauloelr Oi, Meu nome é Paulo Eduardo Eu não estou usando sintetizador de voz
  • 4. Um Pouco de História
  • 5. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD
  • 6. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto
  • 7. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto 2007 - Versão 1.0
  • 8. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto 2007 - Versão 1.0 2012 - Versão 2.0
  • 9. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto 2007 - Versão 1.0 2012 - Versão 2.0 2015 - Versão 2.5
  • 10. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto 2007 - Versão 1.0 2012 - Versão 2.0 2015 - Versão 2.5 2016 - Versão 3.0
  • 11. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD 2005 - Início do Projeto 2007 - Versão 1.0 2012 - Versão 2.0 Performance: Curva de Aprendizado: Facilidade de Uso: Suporte da Comunidade: Qualidade da Documentação: Qualidade do Código: Cobertura de Testes Compatibilidade 2015 - Versão 2.5 2016 - Versão 3.0
  • 12. Previsão de Lançamento em 2016 Suporte ao PHP 5.6+ Com Suporte à Namespaces (PSR-4) Framework FullStack como Meta-Repositório Minimas Dependencias Entre Componentes Aplicações Baseadas em Módulos ou Middlewares Melhorias Técnicas Implementadas Muito Mais Leve e Rápido Suporte Oficial ao PHPUnit Ausência de ORM (Somente TableGateway) Suporte a Doctrine, Propel e Outros (Módulos) Baixa Quebra de Compatibilidade com Versão 2.x Zend Framework 3 Primeira Versão Estável Lançada em 2012 Suporte ao PHP 5.3.3+ (5.5+ Após 2.5.0) Com Suporte à Namespaces (Padrão PHP) Suporte ao Composer (Inclusive para Componentes) Médias Dependências Entre Componentes Aplicações Baseadas em Módulos Melhorias Técnicas Implementadas Menos Pesado (Ainda um Pouco) Suporte Oficial ao PHPUnit Ausência de ORM (Somente TableGateway) Suporte a Doctrine, Propel e Outros (Módulos) Alta Quebra de Compatibilidade com Versão 1.x Zend Framework 2 Primeira Versão Estável Lançada em 2007 Suporte ao PHP 5.1.4+ (5.2.3+ Recomendada) Sem Suporte à Namespaces (Uso Alternativo) Sem Suporte a Composer (Instalação Manual) Componentes Altamento Acoplados Ausência de Módulos Uso de Técnicas Consideradas Antipatterns Bastante Pesado Sem Suporte Oficial a Testes Unitários Componente de ORM Próprio Sem Suporte a Outros ORM’s Retrocompatbilidade com Versões Anteriores Zend Framework 1
  • 13. Os Pilares do Zend Framework 2
  • 15. O Que são Módulos? Our ultimate goal is extensible programming. By this, we mean the construction of hierarchies of modules, each module adding new functionality to the system Niklaus Wirth
  • 16. Características do Module Manager Gerencia os Módulos Mescla as Configurações Gerencia as Dependências Extensibilidade de Módulos Sobrescrita de Módulos
  • 17. Autoload de Modules <?php return [ 'modules' => [ 'Sample' ], 'module_listener_options' => [ 'config_glob_paths' => [ 'config/autoload/{,*.}{global,local}.php' ], 'module_paths' => [ './module', './vendor' ] ] ]; config/application.config.php Formatos: .phar, .phar.gz, .phar.bz2, .phar.tar, .phar.tar.gz, .phar.tar.bz2, .phar.zip, .tar, .tar.gz, .tar.bz2, e .zip. <?php chdir(dirname(__DIR__)); /** @noinspection PhpIncludeInspection */ require 'vendor/autoload.php'; /** @noinspection PhpIncludeInspection */ ZendMvcApplication::init(require 'config/application.config.php')->run(); index.php
  • 18. Módulos no Zend Framework 2 <?php namespace Sample; class Module{} Module.php
  • 19. Módulos no Zend Framework 2 <?php namespace Sample; class Module { public function getConfig() { return include __DIR__ . ‘/../config/module.config.php’; } } Module.php
  • 20. Módulos no Zend Framework 2 <?php namespace Sample; use ZendStdlibArrayUtils; class Module { public function getConfig() { $config = []; $configFiles = [ __DIR__ . ‘/../config/module.config.php’, __DIR__ . ‘/../config/service.config.php’, ]; foreach ($configFiles as $configFile) { $config = ArrayUtils::merge($config, include $configFile); } return $config; } } Module.php
  • 30. Configuration Merge <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘type’ => ‘Literal’, ‘options’ => [ ‘route’ => ‘/user’, ‘defaults’ => [ ‘__NAMESPACE__’ => ‘SampleController’, ‘controller’ => ‘User’, ‘action’ => ‘index’, ],],],],],]; Módulo de Terceiro (ThirdUser)
  • 31. Configuration Merge <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘type’ => ‘Literal’, ‘options’ => [ ‘route’ => ‘/user’, ‘defaults’ => [ ‘__NAMESPACE__’ => ‘SampleController’, ‘controller’ => ‘User’, ‘action’ => ‘index’, ],],],],],]; Módulo de Terceiro (ThirdUser) <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘options’ => [ ‘route’ => ‘admin/user’, ], ], ], ], ]; Meu Módulo (MyUser)
  • 32. Configuration Merge <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘type’ => ‘Literal’, ‘options’ => [ ‘route’ => ‘/user’, ‘defaults’ => [ ‘__NAMESPACE__’ => ‘SampleController’, ‘controller’ => ‘User’, ‘action’ => ‘index’, ],],],],],]; Módulo de Terceiro (ThirdUser) <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘options’ => [ ‘route’ => ‘admin/user’, ], ], ], ], ]; Meu Módulo (MyUser) <?php return [ ‘modules’ => [ ‘ThirdUser’, ‘MyUser’ ], ]; config/application.config.php
  • 33. Configuration Merge <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘type’ => ‘Literal’, ‘options’ => [ ‘route’ => ‘/user’, ‘defaults’ => [ ‘__NAMESPACE__’ => ‘SampleController’, ‘controller’ => ‘User’, ‘action’ => ‘index’, ],],],],],]; Módulo de Terceiro (ThirdUser) <?php return [ ‘router’ => [ ‘routes’ => [ ‘user’ => [ ‘options’ => [ ‘route’ => ‘admin/user’, ], ], ], ], ]; Meu Módulo (MyUser) <?php return [ 'router' => [ 'routes' => [ 'user' => [ 'type' => 'Literal', 'options' => [ 'route' => 'admin/user', 'defaults' => [ '__NAMESPACE__' => 'SampleController', 'controller' => 'User', 'action' => 'index', ], ], ], ], ], ]; Resultado <?php return [ ‘modules’ => [ ‘ThirdUser’, ‘MyUser’ ], ]; config/application.config.php
  • 36. O Que são Serviços? A mechanism to enable access to one or more capabilities, where the access is provided using a prescribed interface and is exercised consistent with constraints and policies as specified by the service description. Organization for the Advancement of Structured Information Standards (OASIS)
  • 37. Características do Service Manager Gerencia os Serviços Injeção de Dependências Inversão do Controle Serviços Modulares Compartilhados ou Independentes
  • 38. Serviços no Zend Framework 2 <?php use SampleUserFormUserFieldset; use SampleUserFormUserFieldsetFactory; use SampleUserFormUserForm; use SampleUserFormUserFormFactory; use SampleUserMapperUserMapperFactory; use SampleUserControllerUserControllerFactory; return [ 'service_manager'=>[ 'factories' => [ 'SampleUserMapperUserMapper' => UserMapperFactory::class, ], ], 'form_elements'=>[ 'factories' => [ UserFieldset::class => UserFieldsetFactory::class, UserForm::class => UserFormFactory::class, ], ], 'controllers'=>[ 'factories' => [ 'SampleUserControllerUser' => UserControllerFactory::class, ], ], ];
  • 39. Serviços no Zend Framework 2 <?php namespace SampleUserForm; use DoctrineCommonPersistenceObjectManager; use DoctrineORMEntityManager; use DoctrineModuleStdlibHydratorDoctrineObject as DoctrineHydrator; use SampleUserEntityUser; use ZendFormFormElementManager; use ZendServiceManagerFactoryInterface; use ZendServiceManagerServiceLocatorInterface; class UserFieldsetFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $formManager) { /** @var $formManager FormElementManager */ $serviceManager = $formManager->getServiceLocator(); /** @var $objectManager ObjectManager */ $objectManager = $serviceManager->get(EntityManager::class); $userFieldset = new UserFieldset(); $userHydrator = new DoctrineHydrator($objectManager, User::class); $userFieldset->setHydrator($userHydrator); $userFieldset->setObject(new User()); return $userFieldset; } }
  • 40. Tipos de Serviços Plugin Manager Config Key Interface Module Method ZendMvcControllerControllerManager controllers ControllerProviderInterface getControllerConfig ZendMvcControllerPluginManager controller_plugins ControllerPluginProviderInterface getControllerPluginConfig ZendFilterFilterPluginManager filters FilterProviderInterface getFilterConfig ZendFormFormElementManager form_elements FormElementProviderInterface getFormElementConfig ZendStdlibHydratorHydratorPluginManager hydrators HydratorProviderInterface getHydratorConfig ZendInputFilterInputFilterPluginManager input_filters InputFilterProviderInterface getInputFilterConfig ZendMvcRouterRoutePluginManager route_manager RouteProviderInterface getRouteConfig ZendSerializerAdapterPluginManager serializers SerializerProviderInterface getSerializerConfig ZendServiceManagerServiceManager service_manager ServiceProviderInterface getServiceConfig ZendValidatorValidatorPluginManager validators ValidatorProviderInterface getValidatorConfig ZendViewHelperPluginManager view_helpers ViewHelperProviderInterface getViewHelperConfig ZendLogProcessorPluginManager log_processors LogProcessorProviderInterface getLogProcessorConfig ZendLogWriterPluginManager log_writers LogWriterProviderInterface getLogWriterConfig services, invokables, factories, abstract_factories
  • 42. O Que são Eventos? An event is an action or occurrence recognised by software that may be handled by the software Wikipedia
  • 43. Características do Event Manager Event Driven Architecture Evento MVC (“Principal“) Integração entre Módulos Eventos Personalizados Compartilhados ou Independentes
  • 44. Eventos no Zend Framework 2 <?php use ZendEventManagerEventManager; use ZendEventManagerEventManagerAwareInterface; use ZendEventManagerEventManagerInterface; class Example implements EventManagerAwareInterface { protected $events; public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers(array( __CLASS__, get_class($this) )); $this->events = $events; } public function getEventManager() { if (!$this->events) { $this->setEventManager(new EventManager()); } return $this->events; } public function doIt($foo, $baz) { $params = compact(‘foo’, ‘baz’); $this->getEventManager()->trigger(__FUNCTION__, $this, $params); } }
  • 45. Eventos no Zend Framework 2 <?php use ZendEventManagerEventManager; use ZendEventManagerEventManagerAwareInterface; use ZendEventManagerEventManagerInterface; class Example implements EventManagerAwareInterface { protected $events; public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers(array( __CLASS__, get_class($this) )); $this->events = $events; } public function getEventManager() { if (!$this->events) { $this->setEventManager(new EventManager()); } return $this->events; } public function doIt($foo, $baz) { $params = compact(‘foo’, ‘baz’); $this->getEventManager()->trigger(__FUNCTION__, $this, $params); } } <?php $example = new Example(); $example->getEventManager()->attach('doIt', function($e) { /** @var $e ZendEventManagerEventInterface */ $event = $e->getName(); $target = get_class($e->getTarget()); // "Example" $params = $e->getParams(); printf( 'Handled event "%s" on target "%s", with parameters %s', $event, $target, json_encode($params) ); }); $example->doIt('bar', 'bat');
  • 46. Eventos no Zend Framework 2 <?php use ZendEventManagerEventManager; use ZendEventManagerEventManagerAwareInterface; use ZendEventManagerEventManagerInterface; class Example implements EventManagerAwareInterface { protected $events; public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers(array( __CLASS__, get_class($this) )); $this->events = $events; } public function getEventManager() { if (!$this->events) { $this->setEventManager(new EventManager()); } return $this->events; } public function doIt($foo, $baz) { $params = compact(‘foo’, ‘baz’); $this->getEventManager()->trigger(__FUNCTION__, $this, $params); } } <?php use ZendEventManagerSharedEventManager; $sharedEvents = new SharedEventManager(); $sharedEvents->attach(‘Example’, ‘do’, function ($e) { /** @var $e ZendEventManagerEventInterface */ $event = $e->getName(); $target = get_class($e->getTarget()); // “Example” $params = $e->getParams(); printf( ‘Handled event “%s” on target “%s”, with parameters %s’, $event, $target, json_encode($params) ); }); $example = new Example(); $example->getEventManager()->setSharedManager($sharedEvents); $example->doIt(‘bar’, ‘bat’);
  • 47. Exemplos de Eventos <?php namespace SampleUserService; use ZendEventManagerEventManager; use ZendEventManagerEventManagerAwareInterface; use ZendEventManagerEventManagerInterface; class UserService implements EventManagerAwareInterface { protected $eventManager; public function addUser($user) { // Logic to Add User $this->getEventManager()->trigger('addUser', null, array('user' => $user)); } public function setEventManager(EventManagerInterface $eventManager) { $eventManager->addIdentifiers(array( get_called_class() )); $this->eventManager = $eventManager; } public function getEventManager() { if (null === $this->eventManager) { $this->setEventManager(new EventManager()); } return $this->eventManager; } }
  • 48. Exemplos de Eventos <?php namespace SampleUser; use ZendMvcMvcEvent; class Module { public function onBootstrap(MvcEvent $event) { $eventManager = $event->getApplication()->getEventManager(); $sharedEventManager = $eventManager->getSharedManager(); $sharedEventManager->attach('SampleUserServiceUserService', 'addUser', function($e) { //Logic to Send User }, 100); } }
  • 49. Exemplos de Eventos <?php namespace SampleUser; use ZendMvcMvcEvent; class Module { public function onBootstrap(MvcEvent $event) { $eventManager = $event->getApplication()->getEventManager(); $sharedEventManager = $eventManager->getSharedManager(); $sharedEventManager->attach('SampleUserServiceUserService', 'addUser', function($e) { //Logic to Send Mail }, 100); } } <?php namespace SampleUser; use ZendMvcMvcEvent; class Module { public function onBootstrap(MvcEvent $event) { $eventManager = $event->getApplication()->getEventManager(); $sharedEventManager = $eventManager->getSharedManager(); $emailListener = new EmailListener(); $emailListener->attachShared($sharedEventManager); } }
  • 50. Exemplos de Eventos <?php namespace SampleUserListener; use ZendEventManagerSharedEventManagerInterface; use ZendEventManagerSharedListenerAggregateInterface; use ZendMvcMvcEvent; class EmailListener implements SharedListenerAggregateInterface { protected $listeners = []; public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100) { $this->listeners[] = $eventManager->attach( ‘SampleUserServiceUserService’, ‘addUser’, [$this, 'onAddUser'], $priority ); } public function detachShared(SharedEventManagerInterface $eventManager) { foreach ($this->listeners as $index => $listener) { if ($eventManager->detach(‘SampleUserServiceUserService’, $listener)) { unset($this->listeners[$index]); } } } public function onAddUser($event) { //Logic to Send User } }
  • 59. Evento MVC <?php namespace PsycoPantheonCoreLayoutListener; use ZendEventManagerSharedEventManagerInterface; use ZendEventManagerSharedListenerAggregateInterface; use ZendMvcMvcEvent; class CrazyListener implements SharedListenerAggregateInterface { protected $listeners = []; public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100) { $this->listeners[] = $eventManager->attach( 'application', MvcEvent::EVENT_DISPATCH, [$this, 'doSomethingCrazy'], $priority ); } public function detachShared(SharedEventManagerInterface $eventManager){//...} public function doSomethingCrazy(MvcEvent $mvcEvent){//Do Something Crazy} }
  • 60. Evento MVC <?php namespace PsycoPantheonCoreLayoutListener; use ZendEventManagerSharedEventManagerInterface; use ZendEventManagerSharedListenerAggregateInterface; use ZendMvcMvcEvent; class CrazyListener implements SharedListenerAggregateInterface { protected $listeners = []; public function attachShared(SharedEventManagerInterface $eventManager, $priority = 100) { $this->listeners[] = $eventManager->attach( 'application', MvcEvent::EVENT_DISPATCH, [$this, 'doSomethingCrazy'], $priority ); } public function detachShared(SharedEventManagerInterface $eventManager){//...} public function doSomethingCrazy(MvcEvent $mvcEvent){//Do Something Crazy} } <?php namespace SampleUser; use ZendMvcMvcEvent; class Module { public function onBootstrap(MvcEvent $event) { $eventManager = $event->getApplication()->getEventManager(); $sharedEventManager = $eventManager->getSharedManager(); $crazyListener = new CrazyListener(); $crazyListener->attachShared($sharedEventManager); } }