Operate with harmony (Symfony2 + AngularJS)

Building an application with those wonderful frameworks.

Louis Lainé
4 min readJun 8, 2014

Abstract

Here’s my solution of the problem, maybe there is another which is less touchy. I succeeded in solving this problem. As I didn’t find any post about this subject, I want to explain you how I did it.

Back end part, the API.

As a web developer i love using Symfony2 for web based php project. The way you making PHP is really nice, clean and stable.

Recently i had to implement a web application based on REST. I chose Symfony to build this app. I looked at the FOSRestBundle, to help me but i found the bundle was quite complex for my app. I decided to build my own.

Indeed the framework allows you to create easily your own API.

On top of the HTTPFondation Component, you can create any type of response via the Response class by setting the right content and headers.

Moreover the Route component allows you to add HTTP method requirements for your routes. In addition to the URL, you can match the incoming request (i.e. GET, HEAD, POST, PUT, DELETE). Thereby, you can have two routes with the same URL using a different method, and for example render a form and submit it with the same URL.

Controller

A custom action rendering JSON

Routing

My API is now setup. I can store datas, return them in JSON matching my routes with HTTP requirements.

Front-end part.

I decided to use AngularJS, in other because of the MVC configuration, declarative user interface, easy DOM manipulations, unit testing with Karma …

After some research, i didn’t find an easy method or way to implement Angular with Symfony.

So i decided (once again), to build my own.

Symfony makes your life simpler to manage assets.

It’s very easy and all you need to do is put all your assets in your src/Foo/FooBarBundle/Resources/public/ folder.

And include them in your templates.

Symfony documentation for Assetic

Using Assetic is nice, but will cause problem with angular.

All those assets are going to be publish in the web/bundles folder with a particular name generate by assetic.

Angular will be lost, and won’t find them.

So i decided to put by myself the javascript in the web/bundles/FooBarBundle/js and …/partials concerning the angular template.

Include them in my base template.

app/Resources/views/base.html.twig

As i want to use multiple template with angular, i need to use the ng-view directive.

So i created a single twig template, located in the views/ folders of my bundle.

app-v2/src/fooBar/fooBarBundle/Resources/views/Default/index.html.twig

This template, is going to be my “main” template for all the angular views.

The last things i did is a little touchy. You need to provide a template each route with the framework.

Angular won’t know where to find them because of the special tree folder of symfony.

To tweak this, i use the document.location object.

So now i can make request to my API in an Angular controller.

--

--