SlideShare a Scribd company logo
Symfony:
Your Next Microframework
by your friend:
Ryan Weaver
@weaverryan
by your friend:
Ryan Weaver
@weaverryan
KnpUniversity.com

github.com/weaverryan
Who is this guy?
> Lead for the Symfony documentation

> KnpLabs US - Symfony Consulting, 

training & general Kumbaya

> Writer for KnpUniversity.com Tutorials
> Husband of the much more 

talented @leannapelham
Thinking about 2
Problems
@weaverryan
Problem 1:

Symfony Sucks
@weaverryan
@weaverryan
@weaverryan
@weaverryan
@weaverryan
Symfony

is too hard
@weaverryan
The Symfony Framework

is too hard
@weaverryan
The components are not usually the
problem
Why?
@weaverryan
Route

Controller

Response
@weaverryan
WTF?
Useful Objects
1) Common tasks require

too much code
@weaverryan
2) Symfony is too big
@weaverryan
Too many files

==

A Perceived Complexity
@weaverryan
@weaverryan
~ 25 files
~ 10 directories
for Hello World
Problem 2:

Is my project 

macro or micro?
@weaverryan
Macro => Use Symfony
@weaverryan
Micro => Use Silex
@weaverryan
The fact we have this
option is incredible

but…
@weaverryan
Silex has a slightly
different tech stack
@weaverryan
Silex doesn’t have bundles
@weaverryan
Silex can’t evolve to a full
stack Symfony App
@weaverryan
What if we just made
Symfony smaller?
@weaverryan
Symfony: Your Next Microframework (SymfonyCon 2015)
6 files
62 lines of code
<?php



use SymfonyComponentHttpKernelKernel;

use SymfonyComponentConfigLoaderLoaderInterface;



class AppKernel extends Kernel

{

public function registerBundles()

{

return array(

new SymfonyBundleFrameworkBundleFrameworkBundle(),

new SymfonyBundleTwigBundleTwigBundle(),

);

}



public function registerContainerConfiguration($loader)

{

$loader->load(

__DIR__.'/config/config_'.$this->getEnvironment().'.yml'

);

}

}
How small can we go?
@weaverryan
What is a Symfony
Application?
@weaverryan
What is a Symfony App?
@weaverryan
1.A set of bundles
2.A container of services
3.Routes
Let’s create a new

Symfony project

from nothing
@weaverryan
{

"require": {

"symfony/symfony": "^2.8"

}

}
@weaverryan
composer.json
<?php



use SymfonyComponentConfigLoaderLoaderInterface;

use SymfonyComponentHttpKernelKernel;



require __DIR__.'/vendor/autoload.php';



class AppKernel extends Kernel

{

public function registerBundles()

{

}



public function registerContainerConfiguration($loader)

{

}

}

index.php
<?php



use SymfonyBundleFrameworkBundleKernelMicroKernelTrait;

use SymfonyComponentDependencyInjectionContainerBuilder;

use SymfonyComponentRoutingRouteCollectionBuilder;
// ...



class AppKernel extends Kernel

{

use MicroKernelTrait;



public function registerBundles()

{

}



protected function configureRoutes(RouteCollectionBuilder $routes)

{

}



protected function configureContainer(ContainerBuilder $c, $loader)

{

}

}

index.php
1) A set of bundles
2) Routes
3) A container of services
public function registerBundles()

{

return array(

new SymfonyBundleFrameworkBundleFrameworkBundle()

);

}
AppKernel
protected function configureContainer(ContainerBuilder $c, $loader)

{

$c->loadFromExtension('framework', array(

'secret' => 'S0ME_SECRET',

));

}
AppKernel
// config.yml
framework:

secret: S0ME_SECRET
protected function configureRoutes(RouteCollectionBuilder $routes)

{

$routes->add('/random/{limit}', 'kernel:randomAction');

}
AppKernel
New in 2.8!
service:methodName
(Symfony’s controller as a service syntax)
public function randomAction($limit)

{

return new JsonResponse(array(

'number' => rand(0, $limit)

));

}
AppKernel
<?php



// ...



require __DIR__.'/vendor/autoload.php';





class AppKernel extends Kernel

{

// ...

}



$kernel = new AppKernel('dev', true);

$request = Request::createFromGlobals();

$response = $kernel->handle($request);

$response->send();

$kernel->terminate($request, $response);

index.php
How many files?
@weaverryan
How many lines of code?
2 files
52 lines of code
This is a full stack
framework
@weaverryan
@weaverryan
1. Service Container
2. Routing
3. Events
4. ESI & Sub-Requests
5. Compatible with 3rd party bundles
Fast as Hell
@weaverryan
The goal is not to create
single-file apps
@weaverryan
Clarity & Control
@weaverryan
Building a
Realistic App
@weaverryan
github.com/weaverryan/docs-micro_kernel
Requirements:
@weaverryan
1. Add some organization
2. Load annotation routes
3. Web Debug Toolbar + Profiler
4. Twig
Reorganize
class AppKernel extends Kernel

{

}

// web/index.php

$kernel = new AppKernel('dev', true);

$request = Request::createFromGlobals();

$response = $kernel->handle($request);

$response->send();
public function registerBundles()

{

$bundles = array(

new FrameworkBundle(),

new TwigBundle(),

new SensioFrameworkExtraBundle()

);



if ($this->getEnvironment() == 'dev') {

$bundles[] = new WebProfilerBundle();

}



return $bundles;

}
app/AppKernel.php
protected function configureContainer(ContainerBuilder $c, $loader)

{

$loader->load(__DIR__.'/config/config.yml');



if (isset($this->bundles['WebProfilerBundle'])) {

$c->loadFromExtension('web_profiler', array(

'toolbar' => true,

'intercept_redirects' => false,

));

}

}
app/AppKernel.php
@weaverryan
app/config/config.yml
framework:

secret: S0ME_SECRET

templating:

engines: ['twig']

profiler: { only_exceptions: false }
@weaverryan
protected function configureContainer(ContainerBuilder $c, $loader)

{

$loader->load(__DIR__.'/config/config.yml');



if (isset($this->bundles['WebProfilerBundle'])) {

$c->loadFromExtension('web_profiler', array(

'toolbar' => true,

'intercept_redirects' => false,

));

}

}
app/AppKernel.php
@weaverryan
Goodbye config_dev.yml
protected function configureRoutes(RouteCollectionBuilder $routes)

{

if (isset($this->bundles['WebProfilerBundle'])) {

$routes->import(

'@WebProfilerBundle/Resources/config/routing/wdt.xml',

'_wdt'

);

$routes->import(

'@WebProfilerBundle/Resources/config/routing/profiler.xml',

'/_profiler'

);

}



$routes->import(__DIR__.'/../src/App/Controller/', '/', 'annotation')

}
app/AppKernel.php
Goodbye routing_dev.yml
Symfony: Your Next Microframework (SymfonyCon 2015)
Clarity & Control
@weaverryan
@weaverryan
protected function configureContainer(ContainerBuilder $c, $loader)

{

$loader->load(__DIR__ . '/config/config.yml');



$c->setParameter('secret', getenv('SECRET'));

$c->loadFromExtension('doctrine', [

'dbal' => [

'driver' => 'pdo_mysql',

'host' => getenv('DATABASE_HOST'),

'user' => getenv('DATABASE_USER'),

'password' => getenv('DATABASE_PASS'),

]

]);

// ...

}
Environment Variables
@weaverryan
protected function configureContainer(ContainerBuilder $c, $loader)

{

$loader->load(__DIR__.'/config/config.yml');



if (in_array($this->getEnvironment(), ['dev', 'test'])) {



$c->loadFromExtension('framework', [

'profiler' => ['only_exceptions' => false]

]);



}



// ...

}
Environment Control
@weaverryan
Build Services
protected function configureContainer(ContainerBuilder $c, $loader)

{

// ...



$c->register('santa.controller', SantaController::class)

->setAutowired(true);



}
@weaverryan
Build Routes
protected function configureRoutes(RouteCollectionBuilder $routes)

{

// ...

$routes->add('/santa', 'AppBundle:Santa:northPole');



$routes->add(‘/naughty-list/{page}’, 'AppBundle:Santa:list')

->setRequirement('list', 'd+')

->setDefault('page', 1);

}
@weaverryan
Bundless
Applications?
Symfony: Your Next Microframework (SymfonyCon 2015)
@weaverryan
Wait, what does a
bundle even give me?
A bundle gives you:
@weaverryan
1. Services
2. A resource root (e.g. path to load templates)
3. Magic functionality (e.g. commands)
4. Shortcuts
(_controller, AppBundle:User)
@weaverryan
1) Services
protected function configureContainer(ContainerBuilder $c, $loader)

{

// ...



$c->register('santa.controller', SantaController::class)

->setAutowired(true);



}
@weaverryan
2) Resource Root
2) Resource Root
protected function configureContainer(ContainerBuilder $c, $loader)

{

// ...



$c->loadFromExtension('twig', [

'paths' => [__DIR__.'/Resources/views' => 'north_pole']

]);

}
public function randomAction($limit)

{

$number = rand(0, $limit);



return $this->render(‘@north_pole/micro/random.html.twig’, [

'number' => $number

]);

}
@weaverryan
3) Magic Functionality
1. Register commands as services
2. Configure Doctrine mappings to load your
Entity directory
@weaverryan
4) Shortcuts
santa:

controller: AppBundle:Santa:xmas

controller: AppBundleControllerSantaController::xmasAction
$em->getRepository('AppBundle:App');

$em->getRepository('AppBundleEntityApp');
@weaverryan
One New Trick
protected function configureRoutes(RouteCollectionBuilder $routes)

{

$routes->import(__DIR__.’@AppBundle/Controller/‘, '/', 'annotation')

}
protected function configureRoutes(RouteCollectionBuilder $routes)

{

$routes->import(__DIR__.'/../src/App/Controller/', '/', 'annotation')

}
Multiple Kernels?
@weaverryan
Multiple kernels, why?
@weaverryan
1. micro service architecture in monolithic
repository
2. performance (less routes, services &
listeners)
Multiple kernels was
always possible
@weaverryan
Now they’re obvious
@weaverryan
// app/ApiKernel.php
class ApiKernel extends Kernel

{

use MicroKernelTrait;



public function registerBundles()

{

$bundles = array(

new FrameworkBundle(),

new SensioFrameworkExtraBundle()

);



return $bundles;

}

}
No TwigBundle
class ApiKernel extends Kernel

{

// ...



protected function configureContainer($c, $loader)

{

$loader->load(__DIR__.'/config/config.yml');

$loader->load(__DIR__.'/config/api.yml');

}

}
Use PHP logic to load share
config, and custom config
class ApiKernel extends Kernel

{

// ...



protected function configureRoutes($routes)

{

$routes->import(

__DIR__.'/../src/Api/Controller/',

'/api',

'annotation'

);

}



public function getCacheDir()

{

return __DIR__.’/../var/cache/api/'
.$this->getEnvironment();

}

}
Load different routes
cacheDir ~= the cache key
Boot the correct kernel
however you want
@weaverryan
// web/index.php
use SymfonyComponentHttpFoundationRequest;



require __DIR__.'/../app/autoload.php';



$request = Request::createFromGlobals();



if (strpos($request->getPathInfo(), '/api') === 0) {

require __DIR__.'/../app/ApiKernel.php';

$kernel = new ApiKernel('dev', true);

} else {

require __DIR__.'/../app/WebKernel.php';

$kernel = new WebKernel('dev', true);

}



$response = $kernel->handle($request);

$response->send();

Symfony: Your Next Microframework (SymfonyCon 2015)
But how does it work?
@weaverryan
There is one person

who *hates* the name

MicroKernelTrait
@weaverryan
@weaverryan
@weaverryan
trait MicroKernelTrait

{

abstract protected function configureRoutes(RouteCollectionBuilder $routes);

abstract protected function configureContainer(ContainerBuilder $c, $loader);



public function registerContainerConfiguration($loader)

{

$loader->load(function ($container) use ($loader) {

$container->loadFromExtension('framework', array(

'router' => array(

'resource' => 'kernel:loadRoutes',

'type' => 'service',

),

));



$this->configureContainer($container, $loader);

});

}



public function loadRoutes(LoaderInterface $loader)

{

$routes = new RouteCollectionBuilder($loader);

$this->configureRoutes($routes);



return $routes->build();

}

}
Closure Loader
New service route loader
So what now?
@weaverryan
I have a big project…
@weaverryan
Use it for clarity
I’m teaching
@weaverryan
Show it for simplicity
I have a small app
@weaverryan
Show it for power
@weaverryan
PHP & Symfony Video Tutorials
KnpUniversity.com
Thank You!

More Related Content

PDF
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
PDF
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
PDF
Keeping the frontend under control with Symfony and Webpack
PDF
Guard Authentication: Powerful, Beautiful Security
PDF
Master the New Core of Drupal 8 Now: with Symfony and Silex
PDF
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
PDF
Symfony & Javascript. Combining the best of two worlds
PDF
Symfony tips and tricks
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Keeping the frontend under control with Symfony and Webpack
Guard Authentication: Powerful, Beautiful Security
Master the New Core of Drupal 8 Now: with Symfony and Silex
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Symfony & Javascript. Combining the best of two worlds
Symfony tips and tricks

What's hot (20)

PDF
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
KEY
Phpne august-2012-symfony-components-friends
PDF
Twig: Friendly Curly Braces Invade Your Templates!
PDF
How Kris Writes Symfony Apps
PDF
Building Cloud Castles - LRUG
PDF
Great Developers Steal
PPTX
Dealing with Continuous Data Processing, ConFoo 2012
PDF
Symfony 2
PDF
A Gentle Introduction to Event Loops
PDF
Symfony tips and tricks
PDF
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
PPT
Dance for the puppet master: G6 Tech Talk
PDF
Microservice Teststrategie mit Symfony2
PPTX
The road to Ember.js 2.0
PDF
Web Crawling with NodeJS
PDF
Controlling The Cloud With Python
PDF
Phinx talk
PDF
Rails 3: Dashing to the Finish
PDF
How to develop modern web application framework
PDF
To Batch Or Not To Batch
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Phpne august-2012-symfony-components-friends
Twig: Friendly Curly Braces Invade Your Templates!
How Kris Writes Symfony Apps
Building Cloud Castles - LRUG
Great Developers Steal
Dealing with Continuous Data Processing, ConFoo 2012
Symfony 2
A Gentle Introduction to Event Loops
Symfony tips and tricks
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Dance for the puppet master: G6 Tech Talk
Microservice Teststrategie mit Symfony2
The road to Ember.js 2.0
Web Crawling with NodeJS
Controlling The Cloud With Python
Phinx talk
Rails 3: Dashing to the Finish
How to develop modern web application framework
To Batch Or Not To Batch
Ad

Viewers also liked (20)

PDF
Composer in monolithic repositories
PDF
Command Bus To Awesome Town
PDF
Hexagonal architecture message-oriented software design
PDF
Models and Service Layers, Hemoglobin and Hobgoblins
PDF
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
PDF
Diving deep into twig
PDF
Get Soaked - An In Depth Look At PHP Streams
ODP
Elastic Searching With PHP
PDF
Techniques d'accélération des pages web
PDF
Automation using-phing
ODP
PHP5.5 is Here
PPTX
Electrify your code with PHP Generators
PDF
The quest for global design principles (SymfonyLive Berlin 2015)
PDF
Doctrine2 sf2Vigo
PDF
WordCamp Cantabria - Código mantenible con WordPress
PDF
Top tips my_sql_performance
PDF
Mocking Demystified
PDF
Understanding Craftsmanship SwanseaCon2015
PDF
Why elasticsearch rocks!
PDF
Writing infinite scalability web applications with PHP and PostgreSQL
Composer in monolithic repositories
Command Bus To Awesome Town
Hexagonal architecture message-oriented software design
Models and Service Layers, Hemoglobin and Hobgoblins
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
Diving deep into twig
Get Soaked - An In Depth Look At PHP Streams
Elastic Searching With PHP
Techniques d'accélération des pages web
Automation using-phing
PHP5.5 is Here
Electrify your code with PHP Generators
The quest for global design principles (SymfonyLive Berlin 2015)
Doctrine2 sf2Vigo
WordCamp Cantabria - Código mantenible con WordPress
Top tips my_sql_performance
Mocking Demystified
Understanding Craftsmanship SwanseaCon2015
Why elasticsearch rocks!
Writing infinite scalability web applications with PHP and PostgreSQL
Ad

Similar to Symfony: Your Next Microframework (SymfonyCon 2015) (20)

PDF
Hands-on with the Symfony2 Framework
PDF
Symfony Nano Framework
PDF
Symfony2 San Francisco Meetup 2009
PDF
Symfony internals [english]
PDF
Symfony 4: A new way to develop applications #ipc19
PDF
Symfony 4: A new way to develop applications #phpsrb
PDF
Symfony 2 (PHP Quebec 2009)
PDF
Symfony quick tour_2.3
PDF
Improve your web and app development with the Symfony3 framework.
PDF
The Naked Bundle - Tryout
PDF
A dive into Symfony 4
PPTX
A soa approximation on symfony
PPTX
A SOA approximation on symfony
PDF
Modularity problems
PPTX
Creating your own framework on top of Symfony2 Components
PDF
Symfony 2 (PHP day 2009)
ODP
An introduction to Symfony 2 for symfony 1 developers
PDF
Symfony 2.0
PDF
Symfony4 - Deep dive
Hands-on with the Symfony2 Framework
Symfony Nano Framework
Symfony2 San Francisco Meetup 2009
Symfony internals [english]
Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #phpsrb
Symfony 2 (PHP Quebec 2009)
Symfony quick tour_2.3
Improve your web and app development with the Symfony3 framework.
The Naked Bundle - Tryout
A dive into Symfony 4
A soa approximation on symfony
A SOA approximation on symfony
Modularity problems
Creating your own framework on top of Symfony2 Components
Symfony 2 (PHP day 2009)
An introduction to Symfony 2 for symfony 1 developers
Symfony 2.0
Symfony4 - Deep dive

More from Ryan Weaver (13)

PDF
Webpack Encore Symfony Live 2017 San Francisco
PDF
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
PDF
Silex: Microframework y camino fácil de aprender Symfony
PDF
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
PDF
The Wonderful World of Symfony Components
PDF
A PHP Christmas Miracle - 3 Frameworks, 1 app
PDF
Symfony2: Get your project started
PDF
Symony2 A Next Generation PHP Framework
PDF
Being Dangerous with Twig (Symfony Live Paris)
PDF
Being Dangerous with Twig
PDF
Doctrine2 In 10 Minutes
PDF
Dependency Injection: Make your enemies fear you
PDF
The Art of Doctrine Migrations
Webpack Encore Symfony Live 2017 San Francisco
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
Silex: Microframework y camino fácil de aprender Symfony
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
The Wonderful World of Symfony Components
A PHP Christmas Miracle - 3 Frameworks, 1 app
Symfony2: Get your project started
Symony2 A Next Generation PHP Framework
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig
Doctrine2 In 10 Minutes
Dependency Injection: Make your enemies fear you
The Art of Doctrine Migrations

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Weekly Chronicles - August'25 Week I
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Modernizing your data center with Dell and AMD
NewMind AI Monthly Chronicles - July 2025
Understanding_Digital_Forensics_Presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
The AUB Centre for AI in Media Proposal.docx
Big Data Technologies - Introduction.pptx
Encapsulation_ Review paper, used for researhc scholars
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm

Symfony: Your Next Microframework (SymfonyCon 2015)