symfony and zend framework together 2009

Post on 15-Feb-2017

20.964 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Using symfony and Zend Framework together

Fabien Potencier

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

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

Fabien Potencier

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

•  Follow me on Twitter: @fabpot

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

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

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:;

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

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

"#### /

books.sensiolabs.com

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

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

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

…and of course many other smaller websites…

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

“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

How many of you use symfony?

T-shirt time

Zend Framework

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

How many of you use Zend Framework?

How many of you use Zend Framework in symfony projects?

How many of you use symfony in Zend Framework projects?

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

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

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 ;)

Zend Framework in symfony projects

Install ZF into symfony

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

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(); } }

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

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

symfony in Zend Framework projects

But wait, symfony is a monolithic framework, right?

A bit of history

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

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

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

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

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

Published Components

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

•  Upcoming –  Request Handler –  Output Escaper

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

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

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

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

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);

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

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); } }

// 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();

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

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

constructors, methods, or directly into fields. »

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

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" : '')); } }

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); } }

DI Hello World example

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

A DI container facilitates objects description and object relationships,

configures and instantiates objects

$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

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;

$message = $container->message;

is roughly equivalent to

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

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; } }

<?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>

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]]

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; } }

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

Output Escaper

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

• 

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); } }

<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) ?>

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

with Matthew Weier O’Pheinney

I will reveal the first alpha release of Symfony 2.0!

symfony-live.com

with Matthew Weier O’Pheinney

… with Matthew Weier O'Phinney as a special guest

symfony-live.com

Questions?

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/

top related