O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

Pilares do Zend Framework 2

270 visualizações

Publicada em

Pilares do Zend Framework 2

Publicada em: Tecnologia
  • Seja o primeiro a comentar

  • Seja a primeira pessoa a gostar disto

Pilares do Zend Framework 2

  1. 1. Os Pilares do Zend Framework 2 Construindo Aplicações Realmente Modulares @Pauloelr
  2. 2. Sobre Mim @Pauloelr Oi, Meu nome é Paulo Eduardo Eu não estou usando sintetizador de voz
  3. 3. Objetivos
  4. 4. Um Pouco de História
  5. 5. Zend Framework Mantenedor: Zend Technologies Líder de Projeto: Matthew Weier O’Phinney Versão Atual: 2.5.3 Licença: BSD
  6. 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. 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. 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. 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. 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. 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. 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. 13. Os Pilares do Zend Framework 2
  14. 14. Module Manager
  15. 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. 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. 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. 18. Módulos no Zend Framework 2 <?php namespace Sample; class Module{} Module.php
  19. 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. 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
  21. 21. ModuleLoaderListener
  22. 22. ModuleLoaderListener AutoloaderListener getAutooaderConfig()
  23. 23. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies()
  24. 24. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() ConfigListener getConfig()
  25. 25. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() InitTrigger init() ConfigListener getConfig()
  26. 26. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() InitTrigger init() ConfigListener getConfig() LocatorRegistrationListener
  27. 27. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() InitTrigger init() ConfigListener getConfig() LocatorRegistrationListener ModuleResolverListener
  28. 28. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() InitTrigger init() ConfigListener getConfig() LocatorRegistrationListener ModuleResolverListener OnBootstrapListener onBootstrap()
  29. 29. ModuleLoaderListener AutoloaderListener getAutooaderConfig() ModuleDependencyCheckerListener getModuleDependencies() InitTrigger init() ConfigListener getConfig() LocatorRegistrationListener ModuleResolverListener OnBootstrapListener onBootstrap() ServiceListener getServiceConfig()
  30. 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. 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. 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. 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
  34. 34. DoctrineORMModule ZfcUser TwbBundle ZfcRbac ZfcTwig http://modules.zendframework.com/
  35. 35. Service Manager
  36. 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. 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. 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. 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. 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
  41. 41. Event Manager
  42. 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. 43. Características do Event Manager Event Driven Architecture Evento MVC (“Principal“) Integração entre Módulos Eventos Personalizados Compartilhados ou Independentes
  44. 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. 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. 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. 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. 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. 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. 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 } }
  51. 51. Evento MVC
  52. 52. MvcEvent::EVENT_BOOTSTRAP bootstrap
  53. 53. MvcEvent::EVENT_BOOTSTRAP bootstrap MvcEvent::EVENT_ROUTE route
  54. 54. MvcEvent::EVENT_BOOTSTRAP bootstrap MvcEvent::EVENT_ROUTE route MvcEvent::EVENT_DISPATCH dispatch
  55. 55. MvcEvent::EVENT_BOOTSTRAP bootstrap MvcEvent::EVENT_ROUTE route MvcEvent::EVENT_DISPATCH dispatch MvcEvent::EVENT_DISPATCH_ERROR dispatch.error
  56. 56. MvcEvent::EVENT_BOOTSTRAP bootstrap MvcEvent::EVENT_ROUTE route MvcEvent::EVENT_DISPATCH dispatch MvcEvent::EVENT_RENDER renderer MvcEvent::EVENT_DISPATCH_ERROR dispatch.error
  57. 57. 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
  58. 58. 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
  59. 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. 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); } }
  61. 61. Novidades
  62. 62. Componentes Modularizados
  63. 63. Middlewares
  64. 64. Conclusão
  65. 65. Dúvidas?
  66. 66. Obrigado a Todos
  67. 67. Obrigado a Todos Agradecimentos PHPSP

×