SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Creating your own framework using
Symfony2 Components
Contents
• Symfony Introduction
• Going OOP with the HttpFoundation Component
• Front controller Pattern
• Routing Component
• HttpKernel Component : The Controller Resolver
• EventDispatcher Component
• HttpKernel Component : TheHttpKernel class
• Dependency-Injection Component
• Technical facts about Symfony
• Final code of our framework
• Resources
Symfony Introduction
Symfony is a reusable set of standalone, decoupled and cohesive PHP components
that solve common web development problems.
Symfony Components
• HttpFoundation
• Routing
• HttpKernel
• Debug
• EventDispatcher
• DependencyInjection
• Security
• Validator
• Yaml
.
Fun to Install !!
{
"require": {
"symfony/http-foundation": "^3.0”,
"symfony/routing": "^3.0",
"symfony/http-kernel": "^3.0",
"symfony/debug": "^3.0“,
"symfony/event-dispatcher": "^3.0“,
"symfony/dependency-injection": "^3.0",
"symfony/yaml": "^3.0",
}
}composer install;
<?php
require_once __DIR__.'/../vendor/autoload.php';
Going OOP with the HttpFoundation Component
$_GET
$_POST
$_COOKIE
$_SESSION
$_FILES
Request
Response
Cookie
Session
UploadedFile
RedirectResponse
documentation
$input = isset($_GET['name']) ? $_GET['name'] : 'World';
header('Content-Type: text/html; charset=utf-8');
printf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'));
Starting with our framwork
// simplex/index.php
require_once __DIR__.'/vendor/autoload.php';
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
$request = Request::createFromGlobals();
$input = $request->get('name', 'World');
$response = new Response(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')));
$response->send();
$ composer require symfony/http-foundation
Lets see code snippet after HttpFoundation (pt1)
Utilising “Front Controller” design pattern
• src/ : source code for our app (not publiciy accessible)
vendor/ : any third-party Libraries
web/ : use to house anything that needs to be accessible from the web server,
including assets & out front controller
Lets see code snippet after implementing FrontController
(pt2)
Mapping URLs with Routing Component
Routing component documentation
Basic parts of routing system
• RouteCollection – contains the route definitions (instances of class Route)
• RequestContext - contains information about Request
• UrlMatcher – performs the mapping of the Request to a single Route
$ composer require symfony/routing
New version of our framework using Routing Component
// simplex/web/index.php
require_once __DIR__.'/vendor/autoload.php';
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../src/routes.php';
$context = new RoutingRequestContext();
$context->fromRequest($request);
$matcher = new RoutingMatcherUrlMatcher($routes, $context);
try {
extract($matcher->match($request->getPathInfo()), EXTR_SKIP);
ob_start();
include sprintf(__DIR__.'/../src/pages/%s.php', $_route);
$response = new Response(ob_get_clean());
} catch (RoutingExceptionResourceNotFoundException $e) {
$response = new Response('Not Found', 404);
} catch (Exception $e) {
$response = new Response('An error occurred', 500);
}
$response->send();
// example.com/src/routes.php
use SymfonyComponentRouting;
$routes = new RoutingRouteCollection();
$routes->add('hello', new RoutingRoute('/hello
array('name' => 'World')));
$routes->add('bye', new RoutingRoute('/bye'))
return $routes;
Lets see code snippet after implementing
RoutingComponent (pt3)
Introducing Controllers in Routing Component
// simplex/src/routes.php
$routes->add('hello', new RoutingRoute('/hello/{name}', array(
'name' => 'World',
'_controller' => function ($request) {
// $foo will be available in the template
$request->attributes->set('foo', 'bar');
$response = render_template($request);
// change some header
$response->headers->set('Content-Type', 'text/plain');
return $response;
}
)));
// simplex/web/index.php
try {
$request->attributes->add($matcher->match($request->getPathInfo()));
} catch (RoutingExceptionResourceNotFoundException $e) {
$response = new Response('Not Found', 404);
} catch (Exception $e) {
$response = new Response('An error occurred', 500);
}
$response = call_user_func($request->attributes->get('_controller'), request);
'_controller' => function ($request) {
// $foo will be available in the template
$request->attributes->set('foo', 'bar');
$response = render_template($request);
// change some header
$response->headers->set('Content-Type','text/plain');
return $response;
}
Lets see code snippet after implementing Controller in
RoutingComponent (pt4)
Introducing Controllers in Routing Component (continued)
$ composer require symfony/http-kernel
A non-desirable side-effect , noticed it ??
HttpKernel Component : The Controller Resolver
Using Controller Resolver
public function indexAction(Request $request)
// won't work
public function indexAction($request)
// will inject request and year attribute from request
public function indexAction(Request $request, $year)
Integrating Controller Resolver in our framework
Lets see code snippet after implementing
ControllerResolver (pt5)
This completes part 1 of series
Projects using Symfony2 components
Downsides in our framework code
• We need to copy front.php each time we create a new website.
It would be nice if we could wrap this code into a proper class
Separation of concerns (MVC)
Separation of concerns (MVC) continued..
Separation of concerns (MVC) continued..
Updating routes.php
Lets see code snippet (part - 6)
Separation of concerns (MVC) continued..
Our application has now Four Different layers :
1. web/front.php: The front controller, initializes our application
2. src/Simplex: The reusable framework class
3. src/Calendar: Application specific code (controllers & models)
4. src/routes.php: application specific route configurations
EventDispatcher Component
documentation
On Response Listener
Registering Listener and dispatching event from front controller
Moved listener code into its own class
Lets see code snippet (part - 7)
Using Subscribers instead of Listeners
Registering subscriber
Creating Subscriber
The HttpKernel component
Code implementation part 8
Resources
Resources:
▸ Symfony2 official page https://symfony.com/
▸ Symfony Book
▸ Symfony2 Components
▸ Knp University
▸ Create Framework using Symfony2 components blog
▸ BeIntent Project code structure
THANKS!
Any questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoit
 
Some tips to improve developer experience with Symfony
Some tips to improve developer experience with SymfonySome tips to improve developer experience with Symfony
Some tips to improve developer experience with Symfony
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Ecto and Phoenix: Doing Web With Elixir
Ecto and Phoenix: Doing Web With ElixirEcto and Phoenix: Doing Web With Elixir
Ecto and Phoenix: Doing Web With Elixir
 
170517 damien gérard framework facebook
170517 damien gérard   framework facebook170517 damien gérard   framework facebook
170517 damien gérard framework facebook
 
Symfony3 w duecie z Vue.js
Symfony3 w duecie z Vue.jsSymfony3 w duecie z Vue.js
Symfony3 w duecie z Vue.js
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2
 
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
 
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialAdventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Phoenix demysitify, with fun
Phoenix demysitify, with funPhoenix demysitify, with fun
Phoenix demysitify, with fun
 
Elefrant [ng-Poznan]
Elefrant [ng-Poznan]Elefrant [ng-Poznan]
Elefrant [ng-Poznan]
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Brief Introduction to Ember
Brief Introduction to EmberBrief Introduction to Ember
Brief Introduction to Ember
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 

Andere mochten auch

Skills developed whilst creating the website
Skills developed whilst creating the websiteSkills developed whilst creating the website
Skills developed whilst creating the website
SamanthaWilsonn
 

Andere mochten auch (16)

The Peoples Party!
The Peoples Party!The Peoples Party!
The Peoples Party!
 
Presupuesto publico
Presupuesto publicoPresupuesto publico
Presupuesto publico
 
How i am going to act on feedback
How i am going to act on feedbackHow i am going to act on feedback
How i am going to act on feedback
 
Enhancing Life Skill for Learning to Live Together
Enhancing Life Skill for Learning to Live Together Enhancing Life Skill for Learning to Live Together
Enhancing Life Skill for Learning to Live Together
 
Times Square
Times Square Times Square
Times Square
 
Swachha salila mohapatra
Swachha salila mohapatraSwachha salila mohapatra
Swachha salila mohapatra
 
trabajo diapositivas cassava
trabajo diapositivas cassavatrabajo diapositivas cassava
trabajo diapositivas cassava
 
він
вінвін
він
 
Font Research
Font ResearchFont Research
Font Research
 
Skills developed whilst creating the website
Skills developed whilst creating the websiteSkills developed whilst creating the website
Skills developed whilst creating the website
 
Power system volume-1
Power system volume-1Power system volume-1
Power system volume-1
 
Presentación1
Presentación1Presentación1
Presentación1
 
Pankajini pani
Pankajini paniPankajini pani
Pankajini pani
 
Why We Disagree About Climate Change - Book Review
Why We Disagree About Climate Change - Book ReviewWhy We Disagree About Climate Change - Book Review
Why We Disagree About Climate Change - Book Review
 
Mirror
MirrorMirror
Mirror
 
Evo slides fabio_lo_savio
Evo slides fabio_lo_savioEvo slides fabio_lo_savio
Evo slides fabio_lo_savio
 

Ähnlich wie Creating your own framework on top of Symfony2 Components

Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009
Fabien Potencier
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
Nerd Tzanetopoulos
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptx
SaziaRahman
 

Ähnlich wie Creating your own framework on top of Symfony2 Components (20)

Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
 
Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
Symfony2 for Midgard Developers
Symfony2 for Midgard DevelopersSymfony2 for Midgard Developers
Symfony2 for Midgard Developers
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptx
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
Hands-on with the Symfony2 Framework
Hands-on with the Symfony2 FrameworkHands-on with the Symfony2 Framework
Hands-on with the Symfony2 Framework
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Creating your own framework on top of Symfony2 Components

  • 1. Creating your own framework using Symfony2 Components
  • 2. Contents • Symfony Introduction • Going OOP with the HttpFoundation Component • Front controller Pattern • Routing Component • HttpKernel Component : The Controller Resolver • EventDispatcher Component • HttpKernel Component : TheHttpKernel class • Dependency-Injection Component • Technical facts about Symfony • Final code of our framework • Resources
  • 3. Symfony Introduction Symfony is a reusable set of standalone, decoupled and cohesive PHP components that solve common web development problems. Symfony Components • HttpFoundation • Routing • HttpKernel • Debug • EventDispatcher • DependencyInjection • Security • Validator • Yaml . Fun to Install !! { "require": { "symfony/http-foundation": "^3.0”, "symfony/routing": "^3.0", "symfony/http-kernel": "^3.0", "symfony/debug": "^3.0“, "symfony/event-dispatcher": "^3.0“, "symfony/dependency-injection": "^3.0", "symfony/yaml": "^3.0", } }composer install; <?php require_once __DIR__.'/../vendor/autoload.php';
  • 4. Going OOP with the HttpFoundation Component $_GET $_POST $_COOKIE $_SESSION $_FILES Request Response Cookie Session UploadedFile RedirectResponse documentation
  • 5. $input = isset($_GET['name']) ? $_GET['name'] : 'World'; header('Content-Type: text/html; charset=utf-8'); printf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')); Starting with our framwork // simplex/index.php require_once __DIR__.'/vendor/autoload.php'; use SymfonyComponentHttpFoundationRequest; use SymfonyComponentHttpFoundationResponse; $request = Request::createFromGlobals(); $input = $request->get('name', 'World'); $response = new Response(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'))); $response->send(); $ composer require symfony/http-foundation
  • 6. Lets see code snippet after HttpFoundation (pt1)
  • 7. Utilising “Front Controller” design pattern • src/ : source code for our app (not publiciy accessible) vendor/ : any third-party Libraries web/ : use to house anything that needs to be accessible from the web server, including assets & out front controller
  • 8. Lets see code snippet after implementing FrontController (pt2)
  • 9. Mapping URLs with Routing Component Routing component documentation Basic parts of routing system • RouteCollection – contains the route definitions (instances of class Route) • RequestContext - contains information about Request • UrlMatcher – performs the mapping of the Request to a single Route $ composer require symfony/routing
  • 10. New version of our framework using Routing Component // simplex/web/index.php require_once __DIR__.'/vendor/autoload.php'; $request = Request::createFromGlobals(); $routes = include __DIR__.'/../src/routes.php'; $context = new RoutingRequestContext(); $context->fromRequest($request); $matcher = new RoutingMatcherUrlMatcher($routes, $context); try { extract($matcher->match($request->getPathInfo()), EXTR_SKIP); ob_start(); include sprintf(__DIR__.'/../src/pages/%s.php', $_route); $response = new Response(ob_get_clean()); } catch (RoutingExceptionResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred', 500); } $response->send(); // example.com/src/routes.php use SymfonyComponentRouting; $routes = new RoutingRouteCollection(); $routes->add('hello', new RoutingRoute('/hello array('name' => 'World'))); $routes->add('bye', new RoutingRoute('/bye')) return $routes;
  • 11. Lets see code snippet after implementing RoutingComponent (pt3)
  • 12. Introducing Controllers in Routing Component // simplex/src/routes.php $routes->add('hello', new RoutingRoute('/hello/{name}', array( 'name' => 'World', '_controller' => function ($request) { // $foo will be available in the template $request->attributes->set('foo', 'bar'); $response = render_template($request); // change some header $response->headers->set('Content-Type', 'text/plain'); return $response; } ))); // simplex/web/index.php try { $request->attributes->add($matcher->match($request->getPathInfo())); } catch (RoutingExceptionResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred', 500); } $response = call_user_func($request->attributes->get('_controller'), request); '_controller' => function ($request) { // $foo will be available in the template $request->attributes->set('foo', 'bar'); $response = render_template($request); // change some header $response->headers->set('Content-Type','text/plain'); return $response; }
  • 13. Lets see code snippet after implementing Controller in RoutingComponent (pt4)
  • 14. Introducing Controllers in Routing Component (continued)
  • 15. $ composer require symfony/http-kernel A non-desirable side-effect , noticed it ??
  • 16. HttpKernel Component : The Controller Resolver Using Controller Resolver public function indexAction(Request $request) // won't work public function indexAction($request) // will inject request and year attribute from request public function indexAction(Request $request, $year)
  • 18. Lets see code snippet after implementing ControllerResolver (pt5) This completes part 1 of series Projects using Symfony2 components
  • 19. Downsides in our framework code • We need to copy front.php each time we create a new website. It would be nice if we could wrap this code into a proper class
  • 21. Separation of concerns (MVC) continued..
  • 22. Separation of concerns (MVC) continued.. Updating routes.php
  • 23. Lets see code snippet (part - 6)
  • 24. Separation of concerns (MVC) continued.. Our application has now Four Different layers : 1. web/front.php: The front controller, initializes our application 2. src/Simplex: The reusable framework class 3. src/Calendar: Application specific code (controllers & models) 4. src/routes.php: application specific route configurations
  • 26. On Response Listener Registering Listener and dispatching event from front controller Moved listener code into its own class
  • 27. Lets see code snippet (part - 7)
  • 28. Using Subscribers instead of Listeners Registering subscriber Creating Subscriber
  • 29. The HttpKernel component Code implementation part 8
  • 30.
  • 31. Resources Resources: ▸ Symfony2 official page https://symfony.com/ ▸ Symfony Book ▸ Symfony2 Components ▸ Knp University ▸ Create Framework using Symfony2 components blog ▸ BeIntent Project code structure