66
Using symfony and Zend Framework together Fabien Potencier

Symfony And Zend Framework Together 2009

Embed Size (px)

Citation preview

Page 1: Symfony And Zend Framework Together 2009

Using symfony and Zend Framework together

Fabien Potencier

Page 2: Symfony And Zend Framework Together 2009

Fabien Potencier •  Serial entrepreneur and developer by passion •  Founder of Sensio

– Web Agency (France and USA) –  Since 1998 –  70 people –  Open-Source Specialists –  Big corporate customers –  Consulting, training, development, web design, … and more

–  Sponsor of a lot of Open-Source projects like symfony and Doctrine

Page 3: Symfony And Zend Framework Together 2009

Fabien Potencier •  Creator and lead developer of symfony… •  and creator and lead developer of some more:

–  symfony components –  Swift Mailer : Powerful component based mailing library for PHP –  Twig : Fexible, fast, and secure template language for PHP –  Pirum : Simple PEAR Channel Server Manager –  Sismo : PHP continuous integration server –  Lime : Easy to use unit testing library for PHP –  Twitto : A web framework in a tweet –  Twittee : A Dependency Injection Container in a tweet –  Pimple : A small PHP 5.3 dependency injection container

Page 4: Symfony And Zend Framework Together 2009

Fabien Potencier

•  Read my technical blog: http://fabien.potencier.org/

•  Follow me on Twitter: @fabpot

•  Fork my code on Github: http://github.com/fabpot/

Page 5: Symfony And Zend Framework Together 2009

symfony

•  Full-stack framework (MVC architecture) •  symfony provides the infrastructure/tools needed for 95% of the web

projects •  Open-Source (MIT License) since 2005 •  Based on

–  11 years of Sensio experience building websites

–  Existing Open-Source projects

Page 6: Symfony And Zend Framework Together 2009

Documentation •  Books in several languages •  All the official documentation is released

under an Open-Source license, and also available as printed books

The symfony 1.2Reference Guide

Fabien Potencier!"##$!%&'"(&"

)

*+,-)"%&.'."(&!"#.#$.!

"#### /

The symfony 1.2 Reference G

uideFabien

Potencier

2ND EDITION2N

D EDITIO

N

PracticalsymfonyCreate professional web applicationswith PHP and symfony 1.2

Fabien Potencier

Practical symfony

symfony 1.2

Doctrine

F. Potencier

!"#$%&'(

!"##$#%&'"(&")

*+,-)"%&.'."(&!"#.#$.#

"#### /

Fabien Potencier

les Cahiersdu Programmeur

Avec la contribution de Hugo Hamon

Mieux développer en PHPavec Symfony et Doctrine

Le tutoriel

Jobeet enrichi

et mis à jour

par le créateur

de Symfony !

!"!"#$%&"

'('#!"#$%&"$%&'()*+,-./)*+

0&123+,45678

Fabien Potencier

!"

!"#$%&"

symfony 1.2

PropelF. Poten

cier9:;

9:;

!"#$%$&'%"$'"(

)*+,("&'-%-"$'!"#-$%-$

"#### .

The symfony 1.2Reference Guide

Fabien Potencier

The symfony 1.2 Reference G

uideFabien

Potencier

symfony

Fabien Potencier

symfony

Fabien Poten

cier

!"#$!%&%'"$%"(

)*+,("&%-'-"$%!"#-$!-%

"#### .

!"#$%&

!"#$%&

!"!"#$%&"

'('#!"#$%&"$%&'()*+,-./)*+

0&123+,45678

Fabien Potencier

!"!"#$%&"

symfony 1.2

Doctrine

F. Potencier

!"#$%&'(

9:;

9:;

!"#$$%&'("$'")

*+,-)"&'.(."$'!"#.$$.%

"#### /

Page 7: Symfony And Zend Framework Together 2009

books.sensiolabs.com

Page 8: Symfony And Zend Framework Together 2009

Very active community

Mailing-lists / forum / IRC

More than 750 plugins with about 1-2 new plugins a day

700 000 visitors per month on symfony-project.org

Page 9: Symfony And Zend Framework Together 2009

Used to build the largest websites

•  Yahoo! Bookmarks sf-to.org/bookmarks

•  Yahoo! Answers sf-to.org/answers

•  delicious.com sf-to.org/delicious

•  Dailymotion sf-to.org/dailymotion

Page 10: Symfony And Zend Framework Together 2009

Dailymotion is the second most popular video sharing website

One of the top 30 websites in the world

59 million unique users in July 2009

Page 11: Symfony And Zend Framework Together 2009

…and of course many other smaller websites…

Page 12: Symfony And Zend Framework Together 2009

Roadmap

•  1.0 – January 2007 •  1.1 – June 2008 •  1.2 – November 2008 •  1.3 – November 2009 •  1.4 – Last 1.X version

– same as 1.3 but with all deprecated features removed •  Version 2.0 – First alpha early 2010

Page 13: Symfony And Zend Framework Together 2009

“Enterprise” version Version 1.0 LTS: Maintained for 3 years Version 1.1, 1.2, 1.3: Maintained for 1 year Version 1.4 LTS: Maintained for 3 years

Regular releases – Bug and security fixes, compatibility with newer PHP versions

– No new feature (even small ones)

– Upgrading is simple and safe

Page 14: Symfony And Zend Framework Together 2009

How many of you use symfony?

Page 15: Symfony And Zend Framework Together 2009

T-shirt time

Page 16: Symfony And Zend Framework Together 2009

Zend Framework

•  Library of components with a MVC layer •  New BSD license •  Open-Source since 2007

How many of you use Zend Framework?

Page 17: Symfony And Zend Framework Together 2009
Page 18: Symfony And Zend Framework Together 2009

How many of you use Zend Framework in symfony projects?

Page 19: Symfony And Zend Framework Together 2009

How many of you use symfony in Zend Framework projects?

Page 20: Symfony And Zend Framework Together 2009

Using symfony and Zend Framework together?

•  Both are plain PHP projects •  Both use Subversion •  Both use a PHP autoloader

•  So, using both in a project is, well, trivial

Page 21: Symfony And Zend Framework Together 2009

Using symfony and Zend Framework together?

•  Of course, people find it weird because both are MVC frameworks •  But both have more than just the MVC part

•  Using them both in a project means –  Choosing one for the structure (controller, project organization, structure, and

configuration) –  Choosing the components/libraries, based on your needs and their strengths

Page 22: Symfony And Zend Framework Together 2009

Using symfony and Zend Framework together?

•  I like this approach a lot because: –  I don't like to reinvent the wheel –  symfony itself started its life as a glue between existing components –  and symfony is still based on some third-party libraries

•  Propel •  Doctrine •  Swift Mailer •  …

•  Of course, I like it even more if you use Zend Framework within a symfony project ;)

Page 23: Symfony And Zend Framework Together 2009

Zend Framework in symfony projects

Page 24: Symfony And Zend Framework Together 2009

Install ZF into symfony

Put library/Zend/ files into lib/vendor/Zend

Page 25: Symfony And Zend Framework Together 2009

Setup autoloading // config/ProjectConfiguration.class.php class ProjectConfiguration extends sfProjectConfiguration { public function setup() { $this->enablePlugins(array('sfDoctrinePlugin'));

set_include_path(sfConfig::get('sf_lib_dir').'/vendor'.PATH_SEPARATOR.get_include_path()); require_once sfConfig::get('sf_lib_dir').'/vendor/Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); } }

Page 26: Symfony And Zend Framework Together 2009
Page 27: Symfony And Zend Framework Together 2009

What people use?

•  Pretty much everything except the MVC part: –  Zend_Search_Lucene –  Zend_OpenId –  Zend_Amf –  Zend_Feed –  Zend_Ldap –  Zend_Pdf –  Zend_Service –  Zend_Soap

Page 28: Symfony And Zend Framework Together 2009

Already well documented

•  In the Jobeet tutorial •  and Practical symfony book •  Chapter 17 (symfony 1.3) explains

the configuration and how to use Zend_Search_Lucene

2ND EDITION2N

D EDITIO

N

PracticalsymfonyCreate professional web applicationswith PHP and symfony 1.2

Fabien Potencier

Practical symfony

symfony 1.2

Doctrine

F. Potencier

!"#$%&'(

!"##$#%&'"(&")

*+,-)"%&.'."(&!"#.#$.#

"#### /

http://www.symfony-project.org/jobeet/1_3/Doctrine/en/17

Page 29: Symfony And Zend Framework Together 2009

symfony in Zend Framework projects

Page 30: Symfony And Zend Framework Together 2009

But wait, symfony is a monolithic framework, right?

Page 31: Symfony And Zend Framework Together 2009

A bit of history

symfony 1.0 (January 2007) started as a glue between existing Open-Source libraries

Page 32: Symfony And Zend Framework Together 2009

A bit of history

symfony 1.1 (June 2008) was a big refactoring of the code base

–  Decoupled but cohesive components: the symfony component like Forms, Routing, Cache, YAML, ORMs, …

platform

sfEventDispatcher

sfRequest sfResponsesfRouting sfUser

sfStorage sfCache

sfI18N

sfForm

sfLogger

sfDatabase

sfValidator sfWidget

sfYAML

sfCoreAutoload

sfOutputEscaper

Page 33: Symfony And Zend Framework Together 2009

The symfony MVC framework is based on a set of cohesive but decoupled classes, the symfony components

Page 34: Symfony And Zend Framework Together 2009

Symfony Components

•  Standalone components •  Packaged individually •  Dedicated website for each component (with code and documentation)

–  http://components.symfony-project.org/ •  Dedicated Subversion and Git repository

–  http://svn.symfony-project.com/components/ –  http://github.com/fabpot

Page 35: Symfony And Zend Framework Together 2009

symfony components

•  Extracted from symfony –  Event dispatcher –  YAML –  Output Escaping

•  Written from scratch for Symfony 2 –  Dependency Injection Container –  Request Handler

•  We won’t duplicate effort with ZF

Page 36: Symfony And Zend Framework Together 2009

Published Components

•  Already published components: –  YAML –  Dependency Injection –  Event Dispatcher –  Templating

•  Upcoming –  Request Handler –  Output Escaper

Page 37: Symfony And Zend Framework Together 2009

symfony components in a ZF project

•  symfony components can make your ZF application better – More configurable: symfony YAML – More flexible: symfony Event Dispatcher –  Faster: symfony Dependency Injection – More secure: symfony Output Escaper

•  … and more fun of course

Page 38: Symfony And Zend Framework Together 2009

symfony components in a ZF project

•  The examples in this presentation are just to get you started faster

•  So, be creative with them. They open all kind of opportunities for your next Zend Framework project

•  And please, give me feedback, and tell me what you do with the symfony components

Page 39: Symfony And Zend Framework Together 2009

YAML

•  YAML is a human friendly data serialization standard for all programming languages (implementations exist in Perl, Ruby, Python, Java, …)

•  YAML is a great format for your configuration files •  YAML files are as expressive as XML files and as readable as INI files

Page 40: Symfony And Zend Framework Together 2009

YAML

•  Used in symfony for all configuration files •  Used in Doctrine for schema and fixtures •  Can be used in Zend Framework for the same purposes

Page 41: Symfony And Zend Framework Together 2009

require_once '/path/to/sfYaml.php';

// Parse YAML $config = sfYaml::load(<<<EOF config: key: value foo: [foo, bar] bar: { foo: bar } foobar: { foo: [foo, bar] } EOF );

// Dump YAML sfYaml::dump($config);

Page 42: Symfony And Zend Framework Together 2009

Event Dispatcher

•  Symfony Event Dispatcher is a PHP library that provides a lightweight implementation of the Observer design pattern

•  Based on the Cocoa Notification Center •  Used in symfony to provide hooks and allow customizations of default

behaviors –  Inject the Web Debug Toolbar –  Inject methods into core Objects –  I18n management – …

platform

sfEventDispatcher

sfRequest sfResponsesfRouting sfUser

sfStorage sfCache

sfI18N

sfForm

sfLogger

sfDatabase

sfValidator sfWidget

sfYAML

sfCoreAutoload

sfOutputEscaper

Page 43: Symfony And Zend Framework Together 2009

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public function run() { require_once '/path/to/sfEventDispatcher.php'; $dispatcher = new sfEventDispatcher();

$event = new sfEvent(null, 'bootstrap.prerun'); $dispatcher->notify($event);

parent::run();

$event = new sfevent(null, 'bootstrap.postrun'); $dispatcher->notify($event); } }

Page 44: Symfony And Zend Framework Together 2009

// register a listener $dispatcher->connect('event_name', array($this, 'callback'));

// notify an event $event = new sfEvent($this, 'event_name', $parameters); $dispatcher->notify($event);

$dispatcher->notifyUntil($event); if (!$event->isProcessed()) { // ... }

$dispatcher->filter($event, $value); $value = $event->getReturnValue();

Page 45: Symfony And Zend Framework Together 2009

Dependency Injection Container

•  Symfony Dependency Injection is a PHP library that provides a lightweight Dependency Injection Container

•  … for classes that implement the Dependency Injection pattern –  This is the case for symfony classes –  This is mostly the case for Zend Framework classes

•  Based on the Java Spring framework •  Configuration with PHP, YAML, or XML

Page 46: Symfony And Zend Framework Together 2009

« Dependency Injection is where components are given their dependencies through their

constructors, methods, or directly into fields. »

http://www.picocontainer.org/injection.html

Page 47: Symfony And Zend Framework Together 2009

DI Hello World example class Message { public function __construct(OutputInterface $output, array $options) { $this->output = $output; $this->options = array_merge(array('with_newline' => false), $options); }

public function say($msg) { $this->output->render($msg.($this->options['with_newline'] ? "\n" : '')); } }

Page 48: Symfony And Zend Framework Together 2009

DI Hello World example interface OutputInterface { public function render($msg); }

class Output implements OutputInterface { public function render($msg) { echo $msg; } }

class FancyOutput implements OutputInterface { public function render($msg) { echo sprintf("\033[33m%s\033[0m", $msg); } }

Page 49: Symfony And Zend Framework Together 2009

DI Hello World example

$output = new FancyOutput(); $message = new Message($output, array('with_newline' => true)); $message->say('Hello World');

Page 50: Symfony And Zend Framework Together 2009

A DI container facilitates objects description and object relationships,

configures and instantiates objects

Page 51: Symfony And Zend Framework Together 2009

$container = new sfServiceContainerBuilder();

$container->register('output', 'FancyOutput');

$container-> register('message', 'Message')-> setArguments(array(new sfServiceReference('output'), array('with_newline' => true))) ;

$container->message->say('Hello World!');

DI Container Hello World example

Page 52: Symfony And Zend Framework Together 2009

Get the configuration for the message service

The Message constructor must be given an output service

Get the output object from the container

Create a Message object by passing the constructor arguments

$message = $container->message;

Page 53: Symfony And Zend Framework Together 2009

$message = $container->message;

is roughly equivalent to

$output = new FancyOutput(); $message = new Message($output, array('with_newline' => true));!

Page 54: Symfony And Zend Framework Together 2009

Example from Ben Eberlei (he rocks!): http://www.whitewashing.de/blog/articles/118

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public function getContainer() { if (null === $this->_container) { $this->setContainer($this->_initContainer()); }

return $this->_container; }

protected function _initContainer() { require_once '/path/to/sfServiceContainerAutoloader.php'; sfServiceContainerAutoloader::register();

$container = new sfServiceContainerBuilder();

$loader = new sfServiceContainerLoaderFileXml($container); $loader->load(dirname(__FILE__).'/configs/resources.xml');

return $container; } }

Page 55: Symfony And Zend Framework Together 2009

<?xml version="1.0" ?>

<container xmlns="http://symfony-project.org/2.0/container"> <parameters> <parameter key="mailer.username">foo</parameter> <parameter key="mailer.password">bar</parameter> <parameter key="mailer.class">Zend_Mail</parameter> </parameters> <services> <service id="mail.transport" class="Zend_Mail_Transport_Smtp" shared="false"> <argument>smtp.gmail.com</argument> <argument type="collection"> <argument key="auth">login</argument> <argument key="username">%mailer.username%</argument> <argument key="password">%mailer.password%</argument> <argument key="ssl">ssl</argument> <argument key="port">465</argument> </argument> </service> <service id="mailer" class="%mailer.class%"> <call method="setDefaultTransport"> <argument type="service" id="mail.transport" /> </call> </service> </services> </container>

Page 56: Symfony And Zend Framework Together 2009

parameters: mailer.username: foo mailer.password: bar mailer.class: Zend_Mail

services: mail.transport: class: Zend_Mail_Transport_Smtp arguments: [smtp.gmail.com, { auth: login, username: %mailer.username%, password: %mailer.password%, ssl: ssl, port: 465 }] shared: false mailer: class: %mailer.class% calls: - [setDefaultTransport, [@mail.transport]]

Page 57: Symfony And Zend Framework Together 2009

class GuestbookController extends Zend_Controller_Action { public function indexAction() { $guestbook = new Default_Model_Guestbook(); $this->view->entries = $guestbook->fetchAll();

$container = $this->getInvokeArg('bootstrap')->getContainer(); $mailer = $container->mailer; } }

Page 58: Symfony And Zend Framework Together 2009

Dependency Injection Container

•  By default in ZF, new resources can be added to the container but cannot be lazy-loaded

–  All resources used by Zend_Application are loaded on every request

•  By using symfony Service Container, the resources are lazy-loaded –  Instances and their dependencies are created the first time you get them

•  Interesting for resources like DB

Page 59: Symfony And Zend Framework Together 2009

Output Escaper

•  Automatic XSS Protection for your templates •  Wraps your template variables •  Works for strings, arrays, objects, … •  Works for deep method calls

Page 60: Symfony And Zend Framework Together 2009

• 

require_once '/path/to/sfOutputEscaperAutoloader.php'; sfOutputEscaperAutoloader::register();

class My_View extends Zend_View { public function __set($key, $val) { if ('_' === substr($key, 0, 1)) { // throw an exception }

$this->$key = sfOutputEscaper::escape(array($this, 'escape'), $val); } }

Page 61: Symfony And Zend Framework Together 2009

<dl> <?php foreach ($this->entries as $entry): ?> <dt><?php echo $this->escape($entry->email) ?></dt> <dd><?php echo $this->escape($entry->comment) ?></dd> <?php endforeach ?> </dl>

<dl> <?php foreach ($this->entries as $entry): ?> <dt><?php echo $entry->email ?></dt> <dd><?php echo $entry->comment ?></dd> <?php endforeach ?> </dl>

<?php echo $entry->getRawValue()->comment ?>

<?php echo $entry->getComment(ESC_RAW) ?>

Page 62: Symfony And Zend Framework Together 2009

Conclusion

•  Use the right tool for the job •  The PHP community have a lot of great projects

–  Zend Framework –  Symfony –  eZ Components –  Doctrine –  Swift Mailer –  Twig – … and much more

Page 63: Symfony And Zend Framework Together 2009

with Matthew Weier O’Pheinney

I will reveal the first alpha release of Symfony 2.0!

symfony-live.com

Page 64: Symfony And Zend Framework Together 2009

with Matthew Weier O’Pheinney

… with Matthew Weier O'Phinney as a special guest

symfony-live.com

Page 65: Symfony And Zend Framework Together 2009

Questions?

Page 66: Symfony And Zend Framework Together 2009

Sensio S.A. 92-98, boulevard Victor Hugo

92 115 Clichy Cedex FRANCE

Tél. : +33 1 40 99 80 80

Contact Fabien Potencier

fabien.potencier at sensio.com

http://www.sensiolabs.com/

http://www.symfony-project.org/

http://fabien.potencier.org/