The document provides an overview of the Symfony components and how they can be used independently of Symfony frameworks. It discusses how the components like HttpFoundation, HttpKernel, EventDispatcher and Routing can be used to build a basic framework. It encourages developers to learn about these components and leverage them to build applications and share code across different PHP projects.
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
The Wonderful World of Symfony Components
1. The Wonderful World of the
Symfony Components
by your friend:
Ryan Weaver
@weaverryan
Friday, September 28, 12
2. Who is this dude?
• That “Docs” guy
• KnpLabs US - Symfony consulting, training, Kumbaya
• Writer for KnpUniversity.com
screencasts
• Husband of the much more
talented @leannapelham
knplabs.com
@weaverryan github.com/weaverryan
Friday, September 28, 12
3. Intro
Life before components
(The Desert of the Real)
Friday, September 28, 12
10. The Big Bummer :(
• How do I autoload their files?
• Does their library depend on anything else?
• How do I even store their files in my project?
@weaverryan
Friday, September 28, 12
11. Include a Zend Framework 1
component in symfony1
Friday, September 28, 12
16. 2
Components are the key to
mastering your framework
@weaverryan
Friday, September 28, 12
17. 3
If PHP is big, we’ll thrive
If PHP is small, we’ll die
@weaverryan
Friday, September 28, 12
18. Communities
http://www.flickr.com/photos/kitty-kat/
PHP is Huge! Right?
@weaverryan
Friday, September 28, 12
19. PHP > Ruby
@weaverryan
Friday, September 28, 12
20. Fragmentation
http://www.flickr.com/photos/slpunk99/7329609744
But fragmentation makes us tiny, isolated, and
misguided trend-setters
@weaverryan
Friday, September 28, 12
22. I don’t want a damned
CakePHP Plugin!
CakePHP
CodeIgniter
@weaverryan
Friday, September 28, 12
23. Fragmentation
• More information we have to know
• Difficult to hire
• Disjointed forums, StackOverflow
• Interoperability? What’s that?
@weaverryan
Friday, September 28, 12
28. (A)
The Problem of Autoloading
Friday, September 28, 12
29. My Autoloader doesn’t like
your PHPs
• The symfony1 autoloader doesn’t know where ZF1
classes live. The Zf1 autoloader doesn’t know where
symfony1 classes live
• Each library has its own autoloader that you must
discover, configure and use
@weaverryan
Friday, September 28, 12
30. like a town where every
store has its own currency
Friday, September 28, 12
31. From The Mountain:
PSR-0 Class Naming Conventions
“Thou shalt name your classes by
following a predictable pattern”
@weaverryan
Friday, September 28, 12
32. class:
sfRequest
path:
lib/vendor/symfony/???idk
Friday, September 28, 12
33. class:
SymfonyComponentHttpFoundationRequest
path:
vendor/symfony/src/Symfony/Component/
HttpFoundation/Request.php
Friday, September 28, 12
55. Symfony3
$req = Request::createFromGlobals();
if ($req->getPathInfo() == '/') {
$res = new Response('Homepage! o/');
} else {
$res = new Response('sad missing page :/');
}
$res->headers->set('X-SECRET', 'Foo');
$res->send();
Friday, September 28, 12
56. Get some learning about
HttpFoundation
• Docs: http://bit.ly/sf2-http-foundation
• Code: http://bit.ly/sf2-http-foundation-code
• API: http://bit.ly/sf2-http-foundation-api
@weaverryan
Friday, September 28, 12
57. Level 2
HttpKernel
symfony/http-kernel
Friday, September 28, 12
58. Request
Framework
? Determine ?
the controller
?
Execute it
Response
Flush the Response
@weaverryan
Friday, September 28, 12
59. Framework:
A pattern for converting a
request into a response
Friday, September 28, 12
60. Request
Framework
? Determine ?
the controller
?
Execute it
Response
Flush the Response
@weaverryan
Friday, September 28, 12
61. Request
HttpKernel
? Determine ?
the controller
?
Execute it
Response
Flush the Response
@weaverryan
Friday, September 28, 12
62. $kernel = new HttpKernel(...);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
There be magic inside!
Friday, September 28, 12
63. These lines execute your
Symfony application
(hint, see - web/app.php)
Friday, September 28, 12
65. Yea, this is abstract
Stay Tuned...
Friday, September 28, 12
66. Level 3
EventDispatcher
symfony/event-dispatcher
Friday, September 28, 12
67. A classic “observer pattern”
Tell me when Liz
gets to work
Listener
Event
Dispatcher
Listener
Tell me when Liz
gets to work
@weaverryan
Friday, September 28, 12
68. • Event Dispatcher: a classic “observer pattern”
Yo! I’m at
work!
Listener
Event
Dispatcher
Listener
@weaverryan
Friday, September 28, 12
69. • Event Dispatcher: a classic “observer pattern”
Liz is at
work!
Listener
Event
Dispatcher
Listener
Liz is at
work!
@weaverryan
Friday, September 28, 12
70. • Event Dispatcher: a classic “observer pattern”
She’s the best
around!
Listener
Event
Dispatcher
Listener
I’m totally
going to go talk
with her!!
Friday, September 28, 12
71. Level 4
Routing
symfony/routing
Friday, September 28, 12
72. Url
Router
Match against
a route
Route
Return info
about the route
Route
@weaverryan
Friday, September 28, 12
73. $loader = new ClosureLoader();
$router = new Router($loader, function() {
$collection = new RouteCollection();
$route = new Route('/blog/{slug}');
$collection->add('blog', $route);
return $collection;
});
$results = $router->match('/blog/sflive');
array(
'slug' => 'sflive',
'_route' => 'blog',
)
Friday, September 28, 12
74. $loader = new ClosureLoader();
$router = new Router($loader, function() {
$collection = new RouteCollection();
$route = new Route('/blog/{slug}', array(
'_controller' => 'SomeBundle:Blog:show'
));
$collection->add('blog', $route);
return $collection;
});
$results = $router->match('/blog/sflive');
array(
'_controller' => 'SomeBundle:Blog:show',
'slug' => 'sflive',
'_route' => 'blog'
)
Friday, September 28, 12
90. // app.php
require 'vendor/autoload.php';
use SymfonyComponentProcessProcess;
$process = new Process('php dinner.php');
// if dinner takes longer than 5 seconds
// to cook, freak out!
$process->setTimeout(5);
$process->run(function($type, $buffer) {
echo $buffer;
});
// executed after the command finishes
if (!$process->isSuccessful()) {
throw new Exception('Process misbehaved')
}
Friday, September 28, 12
93. $process = new Process('php dinner.php');
$process->start();
// do more work here
echo "WORKING!!! n";
while ($process->isRunning()) {
// wait for the process to finish
};
echo $process->getOutput();
Friday, September 28, 12
95. $process = new Process('php dinner.php');
$process->setStdin('turkey');
“turkey” is read from Stdin
Friday, September 28, 12
96. Handling things that blow up!
$process = new Process('php dinner.php');
$process->run(function($type, $buffer) {
if ($type == 'err') {
// perhaps do some logging?
echo $buffer;
}
});
if (!$process->isSuccessful()) {
echo sprintf(
"Process failed! Exit code %s, '%s'n",
$process->getExitCode(),
$process->getExitCodeText()
);
}
Friday, September 28, 12
97. Find out more about Process
• Docs: http://bit.ly/sf2-process
• Code: http://bit.ly/sf2-process-code
• API: http://bit.ly/sf2-process-api
@weaverryan
Friday, September 28, 12
98. @kriswallsmith
SPORK!
$manager = new SporkProcessManager();
$manager->fork(function() {
// do something in another process!
return 'Hello from '.getmypid();
})->then(function(SporkFork $fork) {
// do something in the parent process afterwards
echo "{$fork->getPid()} says '{$fork->getResult()}'";
});
Fork yourself some more PHP
https://github.com/kriswallsmith/spork
Friday, September 28, 12
99. Finder
symfony/finder
Friday, September 28, 12
100. From the Fablog
use SymfonyComponentsFinderFinder;
$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");
$finder = new Finder();
$finder->name('photos*')
->size('< 100K')
->date('since 1 hour ago');
foreach ($finder->in('s3://bucket-name') as $file) {
// do something
print $file->getFilename()."n";
}
http://fabien.potencier.org/article/44/php-iterators-and-
streams-are-awesome
Friday, September 28, 12
101. Find(er) out more about Finder
• Docs: http://bit.ly/sf2-finder
• Code: http://bit.ly/sf2-finder-code
• API: http://bit.ly/sf2-finder-api
@weaverryan
Friday, September 28, 12
102. New in 2.1!
Filesystem
symfony/filesystem
Friday, September 28, 12
104. // ...
use SymfonyComponentFilesystemFilesystem;
$filesystem = new Filesystem();
$filesystem->copy(
'cowboy.jpg',
's3://my-bucket/cowboy.jpg'
);
$filesystem->copy(
's3://my-bucket/rodeo.mov',
'rodeo.mov'
);
$filesystem->mirror(
'thumbnails',
's3://my-bucket/thumbnails'
);
Friday, September 28, 12
105. // ...
use SymfonyComponentFilesystemFilesystem;
use SymfonyComponentFinderFinder;
$finder = new Finder();
$finder->name('*.jpg')
->date('since 1 hour ago');
->in('thumbs');
$filesystem = new Filesystem();
$filesystem->chmod($finder, 0777);
Friday, September 28, 12
106. // ...
use SymfonyComponentFilesystemFilesystem;
$filesystem = new Filesystem();
$filesystem->touch('foo.txt');
$filesystem->chmod('foo.txt', 0777);
$filesystem->symlink('/some/dir', '/symlink/target')
Friday, September 28, 12
107. Find out more about Filesystem
• Docs: http://bit.ly/sf2-filesystem
• Code: http://bit.ly/sf2-filesystem-code
• API: http://bit.ly/sf2-filesystem-api
@weaverryan
Friday, September 28, 12
108. Console
symfony/console
Friday, September 28, 12
110. <?php
// command.php
$loader = require 'vendor/autoload.php';
$loader->add('App', __DIR__);
use SymfonyComponentConsoleApplication;
use AppCommandEchoCommand;
$app = new Application();
$app->add(new EchoCommand());
$app->run();
Friday, September 28, 12
111. namespace AppCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
class EchoCommand extends Command
{
protected function configure()
{
$this->setName('echo')->addArgument('msg');
}
public function execute(
InputInterface $input,
OutputInterface $output)
{
$output->writeln('Yo '.$input->getArgument('msg'));
}
}
Friday, September 28, 12
113. Find out more about Command
• Docs http://bit.ly/sf2-console
• Code http://bit.ly/sf2-console-code
• API http://api.symfony.com/master/namespaces.html
-> and search for “Console”
@weaverryan
Friday, September 28, 12
114. If you download Composer
in the next 5 minutes, we’ll
throw in a special gift!
Friday, September 28, 12
122. require 'vendor/autoload.php';
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorConstraintValidatorFactory;
// a little setup
$metadata = new ClassMetadataFactory();
$constraintFactory = new ConstraintValidatorFactory();
$validator = new Validator($metadata, $constraintFactory);
Friday, September 28, 12
123. use SymfonyComponentValidatorConstraintsEmail;
$value = 'ryan[AT]knplabs.com';
$email = new Email();
$email->message = 'Invalid! You entered {{ value }}';
$errors = $validator->validateValue($value, $email);
if (count($errors) > 0) {
echo strtr(
$errors[0]->getMessageTemplate(),
$errors[0]->getMessageParameters()
);
}
Friday, September 28, 12
124. 34 Core Validators and counting
• String length See the “Reference”
• Regular expressions
section of the docs
• Ip addresses
• Dates
• Collections
• File size, mime-type, etc
... and the brand new Luhn validator
for credit card numbers thanks to
@merk ----------------------------------->
@weaverryan
Friday, September 28, 12
130. Documentation
Documentation
Documentation
Friday, September 28, 12
131. The Security Component
https://github.com/symfony/symfony-docs/pull/1604
WIP by @matthiasnoback
Friday, September 28, 12
132. Act 3
Kicking ass in the new
PHP eco-system
Friday, September 28, 12
133. The PHP Ecosphere
Symfony is only one part of the picture
• Symfony
• Zend Framework
• EZ Components
• Drupal
• ...
• Individuals
What other stuff exists?
@weaverryan
Friday, September 28, 12
134. How do we find good
libraries?
Friday, September 28, 12
138. Mink
behat/mink
http://mink.behat.org/
By @everzet, written on
Fabien’s childhood computer
Friday, September 28, 12
139. Command a browser, find elements, click
them, and fill out forms
$driver = new BehatMinkDriverSahiDriver('firefox');
$session->visit('http://my_project.dev/some_page.php');
$page = $session->getPage();
$anchor = $page->find('css', '.something');
$anchor->click();
// get the content of the new page
echo $page->getContent();
Friday, September 28, 12
140. Monolog
monolog/monolog
https://github.com/Seldaek/monolog
Your Friend Jordi
Friday, September 28, 12
141. A Logger, where bells and whistles
come standard
use MonologLogger;
use MonologHandlerStreamHandler;
use MonologHandlerFirePHPHandler;
// Create the logger
$logger = new Logger('my_logger');
$logger->pushHandler(new StreamHandler(
__DIR__.'/my_app.log'
));
$logger->pushHandler(new FirePHPHandler());
$logger->addInfo('My logger is now ready');
Friday, September 28, 12