SlideShare a Scribd company logo
1 of 47
Download to read offline
Zend Framework 3
Rostislav Mykhajliw
TrueSocialMetrics Inc.
Decoupling
Standards
Performance
Cleanup!
Components
"zendframework/zend-mvc": "*",
"zendframework/zend-mvc-console": "*",
"zendframework/zend-di": "*",
"zendframework/zend-servicemanager": "*",
"zendframework/zend-eventmanager": "*",
"zendframework/zendframework": "2.*",
ServiceManager / DI
InteropContainerContainerInterface
interface ContainerInterface
{
public function get($id);
public function has($id);
}
Aura-Di, Laravel, Nette-DI, PHP-DI, Pimple,
Symfony-DI, Zend-DI ...
ServiceLocator - DI
Provides integration for zend-di within
zend-servicemanager
"zendframework/zend-servicemanager-di": "*"
ServiceLocator - build everything
public function build($name, array $options = null)
{
// We never cache when using "build"
$name = isset($this->resolvedAliases[$name]) ?
$this->resolvedAliases[$name] : $name;
return $this->doCreate($name, $options);
}
$serviceLocator->build(‘Customer’, [‘name’ => ‘Joe’]); // Joe
$serviceLocator->build(‘Customer’, [‘name’ => ‘Mike’]); // Mike
Never caches custom object builder through ServiceLocator
ServiceLocatorAwareInterface - has gone ...
PluginManagerLocator - removed
You have to inject all your dependencies!
final class AuthentificationController extends AbstractActionController
{
private $service = $service;
public function __construct(AuthentificationService $service)
{
$this->service = $service;
}
}
FactoryInterface - has gone (deprecated) ...
ZendServiceManagerFactoryInterface - zf2
ZendServiceManagerFactoryFactoryInterface - zf3
WAT?
FactoryInterface - has gove (deprecated) ...
final class AuthentificationPluginFactory
{
public function getContainer(ServiceLocatorInterface $serviceLocator)
{
// zf2
if ($serviceLocator instanceof AbstractPluginManager) {
return $serviceLocator->getServiceLocator();
}
// zf3
return $serviceLocator;
}
public function __invoke(ServiceLocatorInterface $serviceLocator)
{
$container = $this->getContainer($serviceLocator);
$repository = $container->get('RepositoryCustomer');
return new AuthentificationPlugin($repository);
}
}
EventManager
EventManager
StaticEventManager - removed!
GlobalEventManager static methods - GONE!
SharedEventAggregateAwareInterface - removed!
EventManager
HALLELUJAH!
(c) gifly.com
EventManager
$application = $e->getApplication();
$eventManager = $application->getEventManager()
$sharedEvenManager = $eventManager->getSharedManager();
ZF2
ZF3
$sharedEvenManager instanceof SharedEventAggregateAwareInterface
!($sharedEvenManager instanceof SharedEventAggregateAwareInterface)
PSR-7 / Middleware
PSR-7 - HTTP Message Interface
function (RequestInterface $request) : ResponseInterface
Middleware
Authentification
App
Session
request response
Middleware
function ($request, $response, $next)
{
return $next(
$request,
$response
);
}
Middleware
Zend Diactoros
PSR-7 implementation
Zend Stratigility
middleware pipes
Zend Expressive
micro framework on top of Zend Diactoros + Zend Stratigility
Middleware pipes are AWESOME!
$app = new ZendStratigilityMiddleWarePipe();
$app->pipe($sessionManager); // always call
$app->pipe('/blog', $blogMiddleware);
$app->pipe('/api', $apiMiddleware);
$app->pipe($myCoreApp);
Middleware pipes are AWESOME!
$apiApp = new ZendStratigilityMiddleWarePipe();
$apiApp->pipe($tokenValidation);
$apiApp->pipe($versionValidation);
$apiApp->pipe($apiMiddleware);
$myApp->pipe($sessionManager); // always call
$myApp->pipe('/blog', $blogMiddleware);
$myApp->pipe($myCoreApp);
$app = new ZendStratigilityMiddleWarePipe();
$app->pipe(‘/api’, $apiApp);
$app->pipe($myApp);
Middleware pipes error handling
$errorhandler = function($error, $request, $response,
$next) {
return $response->end('Internal error:' . $error);
}
$app = new ZendStratigilityMiddleWarePipe();
$app->pipe('/api', $apiMiddleware);
$app->pipe($errorhandler);
JSON + ENCRYPTION
JWT
Middleware - JWT
{
"alg": "HS256",
"typ": "JWT"
}
{
"user": "John Dow",
"role": "admin"
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC
J9.eyJzdWIiOiIxMjM0NTY3ODkwIiwib
mFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iO
nRydWV9.TJVA95OrM7E2cBab30RM
HrHDcEfxjoYZgeFONFh7HgQ
HEADER DATA SIGNATURE
SHA256 (HEADER +
DATA + SECRET)
Middleware - Session + JWT =
PLUSES
Overhead ~ 400 bytes cookies
● - 20 ms on page load (it’s memcache session overhead)
● Scalability
● Independent of storage
Middleware - session
"ocramius/psr7-session" : "*"
"necromant2005/tt-serverless-session" : "*"
Zend
Expressive
DI
Aura-DI
Pimple
Zend-DI
...
ROUTER
Aura-Route
FastRoute
Zend-Router
...
TEMPLATE
Twig
Plates
Zend-View
...
Standalone symphony
Expressive
Expressive
composer create-project zendframework/zend-expressive-skeleton expressive
Which router do you want to use?
[1] Aura.Router
[2] FastRoute
[3] Zend Router
Which container do you want to use for dependency injection?
[1] Aura.Di
[2] Pimple
[3] Zend ServiceManager
Which template engine do you want to use?
[1] Plates
[2] Twig
[3] Zend View
composer serve
Expressive
$app = AppFactory::create();
$app->get('/', $blogApp);
$app->post('/trackback', 'TrackBack');
$app->put('/post/{id}', 'ReplacePost')
->setOptions([
'tokens' => [ 'id' => 'd+' ],
]);
$app->delete('/post/{id}', 'DeletePost')
->setOptions([
'tokens' => [ 'id' => 'd+' ],
]);
$app->patch('/trackback');
$app->get('/api', function($req, $res, $next) {
return new JsonResponse(['ack' => time()]);
});
$app->run();
You can reach the same through config!
Expressive
namespace AppAction;
class MyAction
{
public function __invoke($request, $response, callable $next)
{
$query = $request->getQueryParams();
$message = $query['message'];
return $response->getBody()->write(
'My very unique message ' . $message
);
}
}
Which error handler do you want to use during development?
[1] Whoops
[n] None of the above
Expressive - PIPES
$blog = new BlogMiddleware();
$api = AppFactory::create();
$app = AppFactory::create();
$app->pipe('/api', $api);
$app->pipe('/blog', $blog);
$app->run();
Expressive - ErrorHandling
"filp/whoops": "*"
● Flexible, stack-based error handling
● No required dependencies
● Simple API for dealing with exceptions, trace frames
& their data
● Includes handlers for different response formats
(JSON, XML, SOAP)
Performance
Performance
PHP7
New Data structures
Strict Types
Closures / Traits
Performance
ServiceLocator - 4x faster
EventManager - 10x faster
Routing - 2x faster
Hello world! - 7x times faster
2x faster page loading
3x less memory
Tests
Tests - straight from the heart manual
class AlbumControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(include 'config/application.config.php');
parent::setUp();
}
public function testAlbum()
{
$this->dispatch('/album');
$this->assertResponseStatusCode(200);
}
}
Tests - straight from the heart manual
class AlbumControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(include 'config/application.config.php');
parent::setUp();
}
public function testAlbum()
{
$this->dispatch('/album');
$this->assertResponseStatusCode(200);
}
}
Tests - works
class RedirectControllerTest extends TestCaseController
{
public function testRedirectNonAuthAction()
{
$controller = new RedirectController();
(new EnvironmentBuilder($this))->build($controller, []);
$res = $controller->redirectAction();
$this->assertEquals(['/analytic/metric?ga=redirect-wrong'], $res);
}
}
Tests - works
public function testRedirectAuthAndViewReffererAction()
{
$controller = new RedirectController();
(new EnvironmentBuilder($this))->build($controller, [
['name' => 'Request',
'options' => [
'query' => ['refferer' => 'http://x.com/zzz'],
'server' => ['HTTP_HOST' => 'x.com'],
],
],
]);
$view = $controller->redirectAction();
$this->assertInstanceOf('ZendViewModelViewModel', $view);
$this->assertEquals('http://x.com/zzz', $view->refferer);
}
"necromant2005/tt-test" : "*"
QUESTIONS ?

More Related Content

What's hot

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
ConFoo
 

What's hot (11)

Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
 
Atomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas HunterAtomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas Hunter
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습
 
DEVIEW - 오픈소스를 활용한 분산아키텍처 구현기술
DEVIEW - 오픈소스를 활용한 분산아키텍처 구현기술DEVIEW - 오픈소스를 활용한 분산아키텍처 구현기술
DEVIEW - 오픈소스를 활용한 분산아키텍처 구현기술
 
digitalSTROM Developer Day 2011: Wie Heimelektronik und digitalSTROM zusammen...
digitalSTROM Developer Day 2011: Wie Heimelektronik und digitalSTROM zusammen...digitalSTROM Developer Day 2011: Wie Heimelektronik und digitalSTROM zusammen...
digitalSTROM Developer Day 2011: Wie Heimelektronik und digitalSTROM zusammen...
 
Communication in Node.js
Communication in Node.jsCommunication in Node.js
Communication in Node.js
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
Bring your infrastructure under control with Infrastructor
Bring your infrastructure under control with InfrastructorBring your infrastructure under control with Infrastructor
Bring your infrastructure under control with Infrastructor
 

Viewers also liked

"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай
Fwdays
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 

Viewers also liked (20)

Сергей Яковлев "Техническая сторона email-маркетинга"
Сергей Яковлев "Техническая сторона email-маркетинга"Сергей Яковлев "Техническая сторона email-маркетинга"
Сергей Яковлев "Техническая сторона email-маркетинга"
 
ZF3 introduction
ZF3 introductionZF3 introduction
ZF3 introduction
 
рентабельный код
рентабельный кодрентабельный код
рентабельный код
 
Алексей Демедецкий | Unit testing in swift
Алексей Демедецкий | Unit testing in swiftАлексей Демедецкий | Unit testing in swift
Алексей Демедецкий | Unit testing in swift
 
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
 
"Backbone React Flux" Артем Тритяк
"Backbone React Flux" Артем Тритяк"Backbone React Flux" Артем Тритяк
"Backbone React Flux" Артем Тритяк
 
"Посмотрим на Акку-Джаву" Дмитрий Мантула
"Посмотрим на Акку-Джаву" Дмитрий Мантула"Посмотрим на Акку-Джаву" Дмитрий Мантула
"Посмотрим на Акку-Джаву" Дмитрий Мантула
 
"The Grail: React based Isomorph apps framework" Эльдар Джафаров
"The Grail: React based Isomorph apps framework" Эльдар Джафаров"The Grail: React based Isomorph apps framework" Эльдар Джафаров
"The Grail: React based Isomorph apps framework" Эльдар Джафаров
 
Павел Тайкало: "Apple watch first steps"
Павел Тайкало: "Apple watch first steps"Павел Тайкало: "Apple watch first steps"
Павел Тайкало: "Apple watch first steps"
 
"Fun with JavaScript and sensors" by Jan Jongboom
"Fun with JavaScript and sensors" by Jan Jongboom"Fun with JavaScript and sensors" by Jan Jongboom
"Fun with JavaScript and sensors" by Jan Jongboom
 
"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"
 
Александр Корниенко "Как реально построить Dream-team?"
Александр Корниенко "Как реально построить Dream-team?"Александр Корниенко "Как реально построить Dream-team?"
Александр Корниенко "Как реально построить Dream-team?"
 
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
 
"Хероковая жизнь" Юрий Литвиненко
"Хероковая жизнь" Юрий Литвиненко"Хероковая жизнь" Юрий Литвиненко
"Хероковая жизнь" Юрий Литвиненко
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)
 
"Выучить язык программирования за 25 минут" Дмитрий Мантула
"Выучить язык программирования за 25 минут" Дмитрий Мантула"Выучить язык программирования за 25 минут" Дмитрий Мантула
"Выучить язык программирования за 25 минут" Дмитрий Мантула
 
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
 
Михаил Чалый "Serverless Architectures using .NET and Azure"
Михаил Чалый "Serverless Architectures using .NET and Azure"Михаил Чалый "Serverless Architectures using .NET and Azure"
Михаил Чалый "Serverless Architectures using .NET and Azure"
 

Similar to Ростислав Михайлив "Zend Framework 3 - evolution or revolution"

Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
Michelangelo van Dam
 
Playing with php_on_azure
Playing with php_on_azurePlaying with php_on_azure
Playing with php_on_azure
CEDRIC DERUE
 

Similar to Ростислав Михайлив "Zend Framework 3 - evolution or revolution" (20)

Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)
 
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
 
How to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend FrameworkHow to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend Framework
 
Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)
 
Zf2 phpquebec
Zf2 phpquebecZf2 phpquebec
Zf2 phpquebec
 
Zend
ZendZend
Zend
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
 
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
 
Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick start
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
 
ZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in LilleZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in Lille
 
Foundations of Zend Framework
Foundations of Zend FrameworkFoundations of Zend Framework
Foundations of Zend Framework
 
A quick start on Zend Framework 2
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2
 
TIAD - DYI: A simple orchestrator built step by step
TIAD - DYI: A simple orchestrator built step by stepTIAD - DYI: A simple orchestrator built step by step
TIAD - DYI: A simple orchestrator built step by step
 
Node azure
Node azureNode azure
Node azure
 
Getting up & running with zend framework
Getting up & running with zend frameworkGetting up & running with zend framework
Getting up & running with zend framework
 
Getting up and running with Zend Framework
Getting up and running with Zend FrameworkGetting up and running with Zend Framework
Getting up and running with Zend Framework
 
Playing with php_on_azure
Playing with php_on_azurePlaying with php_on_azure
Playing with php_on_azure
 
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
 
Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)
 

More from Fwdays

More from Fwdays (20)

"What I learned through reverse engineering", Yuri Artiukh
"What I learned through reverse engineering", Yuri Artiukh"What I learned through reverse engineering", Yuri Artiukh
"What I learned through reverse engineering", Yuri Artiukh
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
"Micro frontends: Unbelievably true life story", Dmytro Pavlov
"Micro frontends: Unbelievably true life story", Dmytro Pavlov"Micro frontends: Unbelievably true life story", Dmytro Pavlov
"Micro frontends: Unbelievably true life story", Dmytro Pavlov
 
"Objects validation and comparison using runtime types (io-ts)", Oleksandr Suhak
"Objects validation and comparison using runtime types (io-ts)", Oleksandr Suhak"Objects validation and comparison using runtime types (io-ts)", Oleksandr Suhak
"Objects validation and comparison using runtime types (io-ts)", Oleksandr Suhak
 
"JavaScript. Standard evolution, when nobody cares", Roman Savitskyi
"JavaScript. Standard evolution, when nobody cares", Roman Savitskyi"JavaScript. Standard evolution, when nobody cares", Roman Savitskyi
"JavaScript. Standard evolution, when nobody cares", Roman Savitskyi
 
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 

Ростислав Михайлив "Zend Framework 3 - evolution or revolution"

  • 1. Zend Framework 3 Rostislav Mykhajliw TrueSocialMetrics Inc.
  • 3. Components "zendframework/zend-mvc": "*", "zendframework/zend-mvc-console": "*", "zendframework/zend-di": "*", "zendframework/zend-servicemanager": "*", "zendframework/zend-eventmanager": "*", "zendframework/zendframework": "2.*",
  • 5. InteropContainerContainerInterface interface ContainerInterface { public function get($id); public function has($id); } Aura-Di, Laravel, Nette-DI, PHP-DI, Pimple, Symfony-DI, Zend-DI ...
  • 6. ServiceLocator - DI Provides integration for zend-di within zend-servicemanager "zendframework/zend-servicemanager-di": "*"
  • 7. ServiceLocator - build everything public function build($name, array $options = null) { // We never cache when using "build" $name = isset($this->resolvedAliases[$name]) ? $this->resolvedAliases[$name] : $name; return $this->doCreate($name, $options); } $serviceLocator->build(‘Customer’, [‘name’ => ‘Joe’]); // Joe $serviceLocator->build(‘Customer’, [‘name’ => ‘Mike’]); // Mike Never caches custom object builder through ServiceLocator
  • 8. ServiceLocatorAwareInterface - has gone ... PluginManagerLocator - removed You have to inject all your dependencies! final class AuthentificationController extends AbstractActionController { private $service = $service; public function __construct(AuthentificationService $service) { $this->service = $service; } }
  • 9. FactoryInterface - has gone (deprecated) ... ZendServiceManagerFactoryInterface - zf2 ZendServiceManagerFactoryFactoryInterface - zf3 WAT?
  • 10. FactoryInterface - has gove (deprecated) ... final class AuthentificationPluginFactory { public function getContainer(ServiceLocatorInterface $serviceLocator) { // zf2 if ($serviceLocator instanceof AbstractPluginManager) { return $serviceLocator->getServiceLocator(); } // zf3 return $serviceLocator; } public function __invoke(ServiceLocatorInterface $serviceLocator) { $container = $this->getContainer($serviceLocator); $repository = $container->get('RepositoryCustomer'); return new AuthentificationPlugin($repository); } }
  • 12. EventManager StaticEventManager - removed! GlobalEventManager static methods - GONE! SharedEventAggregateAwareInterface - removed!
  • 14. EventManager $application = $e->getApplication(); $eventManager = $application->getEventManager() $sharedEvenManager = $eventManager->getSharedManager(); ZF2 ZF3 $sharedEvenManager instanceof SharedEventAggregateAwareInterface !($sharedEvenManager instanceof SharedEventAggregateAwareInterface)
  • 16. PSR-7 - HTTP Message Interface function (RequestInterface $request) : ResponseInterface
  • 18. Middleware function ($request, $response, $next) { return $next( $request, $response ); }
  • 19. Middleware Zend Diactoros PSR-7 implementation Zend Stratigility middleware pipes Zend Expressive micro framework on top of Zend Diactoros + Zend Stratigility
  • 20. Middleware pipes are AWESOME! $app = new ZendStratigilityMiddleWarePipe(); $app->pipe($sessionManager); // always call $app->pipe('/blog', $blogMiddleware); $app->pipe('/api', $apiMiddleware); $app->pipe($myCoreApp);
  • 21. Middleware pipes are AWESOME! $apiApp = new ZendStratigilityMiddleWarePipe(); $apiApp->pipe($tokenValidation); $apiApp->pipe($versionValidation); $apiApp->pipe($apiMiddleware); $myApp->pipe($sessionManager); // always call $myApp->pipe('/blog', $blogMiddleware); $myApp->pipe($myCoreApp); $app = new ZendStratigilityMiddleWarePipe(); $app->pipe(‘/api’, $apiApp); $app->pipe($myApp);
  • 22. Middleware pipes error handling $errorhandler = function($error, $request, $response, $next) { return $response->end('Internal error:' . $error); } $app = new ZendStratigilityMiddleWarePipe(); $app->pipe('/api', $apiMiddleware); $app->pipe($errorhandler);
  • 24. Middleware - JWT { "alg": "HS256", "typ": "JWT" } { "user": "John Dow", "role": "admin" } eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC J9.eyJzdWIiOiIxMjM0NTY3ODkwIiwib mFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iO nRydWV9.TJVA95OrM7E2cBab30RM HrHDcEfxjoYZgeFONFh7HgQ HEADER DATA SIGNATURE SHA256 (HEADER + DATA + SECRET)
  • 25. Middleware - Session + JWT = PLUSES Overhead ~ 400 bytes cookies ● - 20 ms on page load (it’s memcache session overhead) ● Scalability ● Independent of storage
  • 26. Middleware - session "ocramius/psr7-session" : "*" "necromant2005/tt-serverless-session" : "*"
  • 30. Expressive composer create-project zendframework/zend-expressive-skeleton expressive Which router do you want to use? [1] Aura.Router [2] FastRoute [3] Zend Router Which container do you want to use for dependency injection? [1] Aura.Di [2] Pimple [3] Zend ServiceManager Which template engine do you want to use? [1] Plates [2] Twig [3] Zend View composer serve
  • 31. Expressive $app = AppFactory::create(); $app->get('/', $blogApp); $app->post('/trackback', 'TrackBack'); $app->put('/post/{id}', 'ReplacePost') ->setOptions([ 'tokens' => [ 'id' => 'd+' ], ]); $app->delete('/post/{id}', 'DeletePost') ->setOptions([ 'tokens' => [ 'id' => 'd+' ], ]); $app->patch('/trackback'); $app->get('/api', function($req, $res, $next) { return new JsonResponse(['ack' => time()]); }); $app->run(); You can reach the same through config!
  • 32. Expressive namespace AppAction; class MyAction { public function __invoke($request, $response, callable $next) { $query = $request->getQueryParams(); $message = $query['message']; return $response->getBody()->write( 'My very unique message ' . $message ); } } Which error handler do you want to use during development? [1] Whoops [n] None of the above
  • 33. Expressive - PIPES $blog = new BlogMiddleware(); $api = AppFactory::create(); $app = AppFactory::create(); $app->pipe('/api', $api); $app->pipe('/blog', $blog); $app->run();
  • 34. Expressive - ErrorHandling "filp/whoops": "*" ● Flexible, stack-based error handling ● No required dependencies ● Simple API for dealing with exceptions, trace frames & their data ● Includes handlers for different response formats (JSON, XML, SOAP)
  • 35.
  • 38. Performance ServiceLocator - 4x faster EventManager - 10x faster Routing - 2x faster Hello world! - 7x times faster
  • 39. 2x faster page loading
  • 41. Tests
  • 42. Tests - straight from the heart manual class AlbumControllerTest extends AbstractHttpControllerTestCase { public function setUp() { $this->setApplicationConfig(include 'config/application.config.php'); parent::setUp(); } public function testAlbum() { $this->dispatch('/album'); $this->assertResponseStatusCode(200); } }
  • 43. Tests - straight from the heart manual class AlbumControllerTest extends AbstractHttpControllerTestCase { public function setUp() { $this->setApplicationConfig(include 'config/application.config.php'); parent::setUp(); } public function testAlbum() { $this->dispatch('/album'); $this->assertResponseStatusCode(200); } }
  • 44. Tests - works class RedirectControllerTest extends TestCaseController { public function testRedirectNonAuthAction() { $controller = new RedirectController(); (new EnvironmentBuilder($this))->build($controller, []); $res = $controller->redirectAction(); $this->assertEquals(['/analytic/metric?ga=redirect-wrong'], $res); } }
  • 45. Tests - works public function testRedirectAuthAndViewReffererAction() { $controller = new RedirectController(); (new EnvironmentBuilder($this))->build($controller, [ ['name' => 'Request', 'options' => [ 'query' => ['refferer' => 'http://x.com/zzz'], 'server' => ['HTTP_HOST' => 'x.com'], ], ], ]); $view = $controller->redirectAction(); $this->assertInstanceOf('ZendViewModelViewModel', $view); $this->assertEquals('http://x.com/zzz', $view->refferer); }