My slides about API Platform from AFUP’s Forum PHP 2015

My slides from this morning at Forum PHP Paris about API Platform:

Open the slides in full screen

Introducing the phpdoc-to-typehint Converter: add scalar type hints and return type declarations to your projects

tl;dr Download phpdoc-to-typehint, it will automatically add scalar type hints and return type declarations to your PHP project using existing PHPDoc annotations.

PHP 7 will be released soon. Scalar type hints and return type declarations introduced in this new release are very interesting because they enforce the use of stricter types in PHP code. They are less error-prone and ease the maintenance. To quote the RFC: “These type declarations allow the PHP runtime to ensure that correctly-typed arguments are passed to functions, and make function signatures more informative.

At, we are always looking how we can improve the quality of some of our long running sensitive projects. On the other hand we are a gang of lazy leftists drinking beers late at night. Updating all our code bases to add scalar type hints and return type declarations will be a pain.

Hopefully, we’ve already done a similar work by writing an exhaustive PHPDoc including @param  and @return  tags describing PHP functions. It allows IDEs and static analysis tools such as Scrutinizr to detect potential bugs early in the development process. Here was born my idea: a tool using existing PHPDoc tags to automatically add scalar type hint and return types.

This command line tool is called phpdoc-to-typehint. You can download it as PHAR file on GitHub.

To use it, just run the following command:

php phpdoc-to-typehint.phar <my-project-directory>



This tool is very experimental and can break your code. Be sure to have a backup of it (but you’re using Git right?) and run your test suite after the conversion. Bug reports are very welcomed.

It supports:

  • functions
  • methods of classes and traits
  • method definitions in interfaces
  • PHPDoc inheritance

The tool tries to preserve the existing indentation of source code files but it can create some strange indentations, especially when it adds return types. Run PHP CS Fixer to make your code following PSR-1 and PSR-2 conventions.

We can go back to the pub.

Symfony Live San Francisco: my slides about how to make high performance API powered webapps with Symfony

I was speaking about cloud computing, APIs and JavaScript Single Page Application at the Symfony Live San Francisco conference. Here are my slides:

Open the slides in full screen

See you at these upcoming PHP conferences

I’ll speak about API Platform and Symfony at some PHP conferences until the end of 2015:

Symfony Live, San Francisco (October 29th)

Leveraging a cloud computing infrastructure to build high performance Symfony webapps

I’ll present how to tune Symfony webapps to be as efficient and as robust as possible thanks to cloud computing platforms.

I’ll detail how to design the webapp from the start to be very efficient on such platforms: we we’ll learn advantages of splitting the backend code (PHP/Symfony) from the frontend code (HTML/JS/CSS) communicating trough a REST API, how to build stateless apps (including auth) that play well with horizontal scalability, and what kind of services can help us to setup in hours a rock solid infrastructure without an army of sysadmins.

Then we will discover how to run a Sf webapp on Heroku + AWS without pain thanks to some tricks and a lot of useful Symfony bundles and PHP libraries.

In the end we will get a Symfony webapp with all assets stored on a CDN, running on Heroku with HHVM behind a reverse-proxy, in full HTTPS, able to survive under very high traffic.

Forum PHP, Paris (November 24th) – in French

API Platform : un framework dédié aux applications API-first

API Platform est un tout nouveau framework PHP qui permet de construire des applications performantes, évolutives et interopérables. Il est basé sur les nouveaux standards du web: JSON-LD, Hydra, et JSON Web Token (JWT). Il est 100% compatible avec Symfony et ses milliers de bundles. Au cours de ce talk je présenterai les concepts sur lesquels il repose à savoir une API REST centrale consommée par différents types de clients tel que des applis web et mobiles (API-first), le pattern Action-Domain-Responder, un système d’évènements puissant et flexible et des composants “standalones”. Je m’attarderai ensuite à montrer comme les fonctionnalités de API Platform rendent la création d’applications web et mobiles modernes, performantes et intéropérables et à la portée de tous grâce à ses multiples fonctionnalités : – Générateur de modèle de données dérivé du vocabulaire (PHPDoc complète, support de l’ORM Doctrine et de la validation Symfony) – Création automatique d’une API REST de niveau 3 (hypermédia) complètement fonctionnelle (CRUD, validation, listes, paginations, filtres, négociation de contenu…) et 100% extensible – Authentification stateless (cookie-less) – Intégration aisée avec de nombreux clients tel que AngularJS, Guzzle, et les applis mobiles – Behavior Driven Development et web acceptance testing avec la distribution adaptée à API Platform de Behat – Découverte et utilisation d’une interface d’administration générique via Hydra Console La présentation sera didactique et accessible aux développeurs PHP de tous niveaux. La construction d’une micro-application suivant cette architecture sera présentée pas à pas.

SymfonyCon, Paris (December 3rd) – with Fabien Gasser

Building high profile webapps with Symfony and API Platform

In a first part we will introduce semantic and linked data technologies supported by Symfony and API Platform: JSON-LD, Hydra and, their contributions to interoperability and a web of data and how to use them, technologies until there the restricted domain of Java such as RDF, SPARQL, triple stores, ontology engines.

In a second part we will give a feedback on the strategy we employed to build a high traffic CMS platform using Symfony, API Platform and AngularJS as technical stack. We will see how an API-first strategy helped us to deliver fluently content on several channels (desktop, mobile apps, connected devices, partners…) and how that strategy helped us to make large teams working together on the same project. We will also see how to leverage Varnish and AWS to absorb gigantic traffic peaks, how pure-JS fit well with that architecture and effects on SEO

In a third part we will give you some tips in order to build an e-commerce platform based on that approach.

See you there!

New in Symfony 2.8/3.0: services autowiring

Symfony 10 years

Symfony 3.0, the next major version of our preferred PHP framework, will be released in a few weeks. Basically, it shares the same code base as Symfony 2.8 but all deprecated features coming from older versions have been removed to simplify the framework and its maintenance:

Symfony 2.8 and 3.0 also come with a lot of new features including (but not limited to) the (awesome) Guard authentication system, LDAP support or a component to guess types of PHP properties. In this post we’ll discover another interesting feature proudly sponsored by I’ve added to the Dependency Injection Component: autowiring.


Autowiring allows to register services in the container with minimal configuration. It is practical in the field of rapid application development, when designing prototypes and in early stages of large projects. It makes it easy to bootstrap an app service graph and eases refactoring:

A demo containing all code snippets shown in this article is available in a dedicated GitHub repository.

Let’s see how it works. To do so we will build a fake API publishing statutes on a Twitter feed obfuscated with ROT13 (a special case of the Caesar cipher).

Start by creating a ROT13 transformer class:

And now a Twitter client using this transformer:

The Dependency Injection Component is now able to automatically register the dependencies of this  TwitterClient class. The twitter_client service definition just need to be marked as autowired:

The autowiring subsystem will parse the constructor of the TwitterClient class and detects its dependencies that way. Here it will find and fill the need for an instance of a  Rot13Transformer.

If an existing service definition (and only one – see below) is of the needed type, it will inject it. Here it’s not the case, but the subsystem is smart enough to automatically register a private service for the Rot13Transformer class and set it as first argument of the twitter_client  service. Again, it can work only if there is one class of the given type. If there are several classes of the same type, you must fallback to the explicit service definition or register a default implementation (I’ll present this feature in a few line).

As you can see, the autowiring feature drastically reduces the amount of configuration required to define a service. No more arguments section! It also makes it easy to change the dependencies of the  TwitterClient class: just add or remove typehinted arguments in the constructor and you’re done. There is no need anymore to search and edit related service definitions.

Here is a typical controller using the twitter_client services:

You can give a try to the API with  curl:

curl -d "user=kevin&key=ABCD&status=Salut" http://localhost:8000/tweet

It should return  OK.

Working with interfaces

This is nice but when the application grows, it’s recommended to code against abstractions instead of implementations: it allows to easily replace some dependencies without modifying the class depending of them.

To follow this best practice, constructor arguments must be typehinted with interfaces and not concrete classes. It allows to replace easily the current implementation if necessary.

Let’s introduce a Rot13TransformerInterface:

Then edit Rot13Transformer to make it implementing the new interface:

And update TwitterClient  to depend of this new interface:

Finally the service definition must be updated because, obviously, the autowiring subsystem isn’t able to find itself the interface implementation to register:

The autowiring subsystem detects that the rot13_transformer service implements the Rot13TransformerInterface and injects it automatically. Even when using interfaces (and you should), building the service graph and refactoring the project is easier than with standard definitions.

Dealing with multiple implementations of the same type

Last but not least, the autowiring feature allows to specify the default implementation of a given type. Let’s introduce a new implementation of the Rot13TransformerInterface returning the result of the ROT13 transformation uppercased:

This class is intended to decorate the standard ROT13 transformer (or any other implementation) and return it uppercased.

We can now refactor the controller to add another endpoint leveraging this new transformer:

The last step is to update service definitions to register this new implementation and a Twitter client using it:

It deserves some explanations. We now have 2 services implementing the  Rot13TransformerInterface. The autowiring subsystem cannot guess the which one to use, this leads to errors like:

Fortunately, the autowiring_types key is here to specify which implementation to use by default. This key can take a list of types if necessary (using a YAML array).

Thanks to this setting, the  rot13_transformer service is automatically injected as argument of the uppercase_rot13_transformer and twitter_client services. For the  uppercase_twitter_client, we use a standard service definition to inject the specific uppercase_rot13_transformer  service.

You now know everything you need to use the new autowiring feature! As this feature is directly available in the Dependency Injection Component, you can leverage it in any project using it, including Drupal 8, API Platform or BackBee once the component have been upgraded to 2.8+.

As for other RAD features such as the FrameworkBundle controller or annotations, keep in mind to not use autowiring in public bundles nor in large projects with complex maintenance needs.

API Platform 1.0 released! Version 2.0 announced.

Spread the word: after months of development the first stable version of the API Platform framework has finally been released!

API Platform is a next-generation PHP web framework designed to create API-first projects easily but without compromise in the field of extensibility and flexibility:

  • Use our awesome code generator to bootstrap a fully-functional data model from vocabularies with ORM mapping and validation (you can also do it manually)
  • Expose in minutes an hypermedia REST API that works out of the box by reusing entity metadata (ORM mapping, validation and serialization) ; that embraces JSON-LD, Hydra and provides a ton of features (CRUD, validation and error handling, relation embedding, filters, ordering…)
  • Enjoy the beautiful automatically generated API documentation (Swagger-like)
  • Add easily JSON Web Token or OAuth authentication
  • Create specs and tests with a developer friendly API context system on top of Behat
  • Develop your website UI, webapp, mobile app or anything else you want using your preferred client-side technologies! Tested and approved with AngularJS (integration included), IonicReact and native mobile apps

First of all I want to thank the more than 40 developers that have contributed a thousand of commits! You’re awesome guys and nothing would have been possible without you.

To follow up with good news, API Platform got a dedicated website and an updated documentation:

Screenshot of the API Platform website


Last but not least, you can also build an API in any existing Symfony 2.7 project!

The era of new generation of web applications powered by standard, semantic and auto-discoverable is just beginning.

Learn now how API Platform will help you to create such applications.

Another important news: the development of API Platform 2.0 has already begun. This new version will include even more awesome changes:

Expect a release of the 2.0 version before the end of the year!

If you want to learn more about API Platform, come to my talks:

  • tomorrow in London (Symfony Live unconference): Discover API Platform
  • October 29-30 in San Francisco (Symfony Live): Leveraging a cloud computing infrastructure to build high performance Symfony webapps
  • December 3 in Paris (Symfony Con): Building high profile webapps with Symfony and API Platform

(more dates to come)

The API Platform is a projet brought to you by

[Slides] Using PSR-7 with Symfony

Here are the slides of my talk of yesterday about PSR-7 and Symfony. Watch them in full screen.

Deploying Symfony and API Platform apps on Heroku easily


I’ve just published a new library and a tutorial to deploy easily Symfony and API Platform applications in Heroku, the popular Platform As A Service.

The tutorial explains how to set up and deploy an application with a database (Heroku Postgres or MySQL ClearDB), using the log managing system provided by Heroku (Logplex) and using environment variables to define Symfony parameters thanks to the DIC.

The library automatically setups Heroku Postgres or MySQL ClearDB thanks to a Composer script.

As usual, the code and the doc are free and available on GitHub. I hope it will help people using that kind of services.

If you want to learn more about using Symfony on Heroku, Tristan Maindron talk about that topic in the Symfony conference of this week in Lille, France.

Talk à propos de PSR-7 et Symfony ce jeudi à Lille

Ce jeudi je donnerai une présentation lors du sfPot de Lille à propos de l’utilisation de PSR-7 avec le framework Symfony. Tristan Maindron interviendra lui au sujet du déploiement de Symfony dans des environnements Heroku-like. Avis aux intéressés, je viens d’ailleurs de publier une petite bibliothèque à ce sujet.

Attention : inscription gratuite mais obligatoire (voir le visuel).

sfPot à Lille sur PSR-7

Vidéo : construire des applications API-centric avec API Platform et Symfony

Voici la vidéo de la présentation que j’ai donné lors du Symfony Live 2015 à propos de API Platform, une solution pour construire des applications web modernes reposant sur une API REST hypermedia et auto-découvrable.