SlideShare ist ein Scribd-Unternehmen logo
1 von 67
Downloaden Sie, um offline zu lesen
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

Weitere Àhnliche Inhalte

Andere mochten auch

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
Sofia Cabral
 
R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15R LaChanse corporate linkedin portfolio 15
R LaChanse corporate linkedin portfolio 15
Russ LaChanse, MBA
 
ReferenceLetterSparebank1
ReferenceLetterSparebank1ReferenceLetterSparebank1
ReferenceLetterSparebank1
henripenri
 

Andere mochten auch (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
 

Ähnlich wie Pilares do Zend Framework 2

Ähnlich wie 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
 
werwer
werwerwerwer
werwer
 
before upload
before uploadbefore upload
before upload
 
latest slide
latest slidelatest slide
latest slide
 
sdfsd
sdfsdsdfsd
sdfsd
 
sadasd
sadasdsadasd
sadasd
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

KĂŒrzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

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); } }