Doctrine postPersist / postUpdate events not firing in Symfony 2?

So let’s say you’ve been tinkering about with the example given on the Symfony 2 manual page for configuring a Doctrine Event Subscriber.

All is good.

Maybe you’ve been through and configured it just like the example, added a subscriber, re-run your fixtures, and everything is tickedyboo.

But then you make a few changes to the subscriber implementation. Maybe it should do something a little differently, and you want to re-save the entity, and get the new implementation to take effect.

Only, it won’t.

You tinker about some more, and everything looks sane. But for some reason, when you go to your form, change nothing, and click the Submit button, the listener just doesn’t seem to take effect.

Strange, eh?

Not exactly.

See, there’s a big ol’ list of lifecycle events that you can hook into, and do funky things with.

But each one has a weird, technical description that doesn’t quite seem to explain what it does in a way that’s easy to comprehend.

If you followed the Symfony documentation example, you might think a postUpdate or postPersist would be triggered whenever you Submit the form. After all, if you stick some debugs in your code, you can see the entity is persisted and the unit of work is flushed.

But yet, your listener doesn’t fire.

Try changing the data in your form, though, and suddenly the listener is triggered.

I’m 100% sure this isn’t a bug. It’s a misunderstanding.

But if you’ve been sat tearing your hair out as to why this damn thing just won’t do your bidding for the last 30 minutes, the only sane solution is to blog about it, and move on.

Hopefully this will save you a headache or two.

#PHPNW2014 Review

Saturday 4th / Sunday 5th October 2014. Manchester. Were you there?

Well, this year I was. I had wanted to go last year, but because I’m a massive noob, I didn’t book a ticket in time. And then they sold out. Such is life.

PHPNW2014 is only the second PHP conference I have ever attendeded. The first, for those interested in such things, was PHPNE2014 (thanks Jeremy!).

The venue was super easy to find – especially with uber-cool satnav Waze. Also, there was a huge multi-story car park about 100 feet away, so aside from their ridiculously small spaces with huge great bollards on either side, just waiting to damage my paintwork, the parking was ample. And at £2 for the entire day, a total bargain.


The conference started in the packed main room – an auditorium setting, which with 400+ people packed in, felt a little cramped. However, the mood was vibrant and being that this was a Saturday, you could be fairly certain that the people attending actually care about PHP (and it’s ecosystem), as it was hardly an excuse to skive off the day job. Unless you work Saturdays.

Anthony Ferrara (IrcMaxell) took charge of the opening keynote, and delivered a really interesting presentation. I liked the mentions of Reddit especially – as that’s one of my favourite php communities – even if it can be fairly polarised. I also learned a few things about the history of the PHP community – GoPHP5 for example.

Immediately after the keynote I decided to check out the uncon. This was something I all but skipped at PHPNE, but this time I was determined to experience more of it.

There were some really interesting talks – I managed to get in:

I caught the uncon twice throughout the day, and I really enjoyed every session. Whereas in the main sessions the crowd were more mixed and varied, in the uncon room I got the sense that the skill level of the audience was more intermediate to advanced. I’m not saying that’s where I fit in, but rather, doing a talk to that audience must be different to a main room talk.

Big thanks to PHP East Midland organisers Antonis and Clinton for sorting out the Uncon.

I must comment on a couple of talks I really enjoyed. Firstly, Mike Bell’s talk on mental health in software development took a lot of guts. I also thought he nailed it. Great talk Mike, well done, and I’m thoroughly impressed you decided to do a talk as part of your recovery.

Secondly, Jakub Zalas’s talk on the Dependency Inversion Principle has already helped me improve my own coding. Awesome. And great use of the pebble watch to control the slides.

Just before dinner I caught Making Kanban Work For You by Jez Halford. A great talk to a packed room. Entertaining, interesting, and good use of the kitten pic 🙂 I learned my trello board system is like re-inventing a wheel two clever Japanese guys figured out, documented, and made a system out of many years ago. My trello boards === Kanbanned.

Dinner: was excellent, really nice bit of Salmon and fresh veg. Super surprising at the standard of dinner – and good brain food to boot 🙂

After dinner I checked out Debugging: Past, Present and Future by Derek Rethans. This guy is super, super smart. He invented Xdebug. A little fun trivia – Xdebug dumps are orange because Netherlands. I did not know this. The rest of the talk was highly technical and interesting. It definitely left my mind a little fried though.

The last talk I caught was Implementing Server Side Data Synchronization for Mobile Apps by Michele Orselli. Again, another technical talk – and I have to admit, I couldn’t take it all in. It was interesting, but being the last talk of the day, my mind was already pretty full. Conceptually, it was very cool though and an interesting approach to solving real world problems in a modern PHP & mobile project.

Then I went home… no free bar for me.


Sunday started in an interesting fashion. I was late to the party as I had to do some last minute nappy changing on my little girl. Unfortunately this meant I walked in to a hugely packed room where Everzet was giving the presentation I was most looking forward to out of the whole conference. It wasn’t even standing room only – it was maxed out.

So, instead, I went to PHP: Under The Hood by Davey Shafik.

The previous two talks on Saturday had left me fried, but feeling refreshed and raring to go, this talk was perfect. It was indepth, technical, and full of stuff I had never heard of before. So thats how PHP does its magic? Colour me impressed. I loved this one. Nerd out.

Next up was: “Should It?” – A New BDD Tool, Pain Not Included! by Richard McIntyre. Interestingly, this was pitched as an alternative to Behat. And in the room sat Everzet. Creator of Behat. Yikes. Tough crowd. However, the arguments portrayed where well thought out and I could really understand Richard’s points and frustrations. The dialog at the end of the talk between Everzet and Richard was awesome. Everzet is a super smart guy, and one who I have ultimate respect for, so to hear him and Richard debate was brilliant.

Last up for me was The Action-Domain-Responder Design Pattern by Tobias Gies. This is something I am really interested in – and if you are, I recommend this blog post for further reading.


I collected all kinds of bits and pieces. The Sky Bet stand gave me a big old bag of goodies – usb pens, pads, normal pens, stickers…

Magma came up trumps with a nice yellow screen cloth. Perfect as I keep losing my macbook one.

From inviqa I got an awesome Symfony beanie. Yes! So full of win.


The Sky Bet team stand out. Although I didn’t win their ipad, I did enjoy the banter. Also, the team at Data Sift are doing some interesting things and their product sounds awesome.

The Crowd

A great mix. As I mentioned at the start, the sort of person who attends a programming conference on their weekend must seriously enjoy their craft. And so, the crowd reflected this.

I met some really nice people – hello if you are reading 😉 And had a great time.

Minor niggles

Coffee / tea was not free flowing enough, only at organised breaks. A cup of tea is essential to keep me functional. I know there was a bar, but I’m not ordering tea from a bar like some rambunctious yahoo.

Sunday started too early. 9am starts and a free bar the night before? What is this madness.


It was awesome, see you at #PHPNW2015.

How I fixed exception ‘Bad credentials’ with FOSUserBundle

Waaaa, no fair, unexpected nasty bug message on prod? Boo.

Yup, this one just caught me out – and thankfully my good buddy, brother, and friend managed to pick it up whilst doing some ad-hoc Quality Assurance checks.

Disclaimer: This site may have been in prod, but only just, this was the first release to live 🙂 So no major foul.

Disclaimer part 2: Yes, there is now a passing Codeception acceptance test to make sure this never happens again 🙂

Ok, so this is the bug message (mainly for Google users benefit):

UPDATE `your_table_name` SET exception 'Symfony\Component\Security\Core\Exception\BadCredentialsException' with message 'Bad credentials' in /var/www/html/
 Stack trace: #0 /var/www/html/ session_start() #1 /var/www/html/ Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start() #2 /var/www/html/ Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->getBag('attributes') #3 /var/www/html/ Symfony\Component\HttpFoundation\Session\Session->get('_security_main') #4 /var/www/html/ Symfony\Component\Security\Http\Firewall\ContextListener->handle(Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #5 [internal function]: Symfony\Component\Security\Http\Firewall->onKernelRequest(Object(Symfony\Component\HttpKernel\Event\GetResponseEvent), 'kernel.request', Object(Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher)) #6 /var/www/html/ call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseEvent), 'kernel.request', Object(Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher)) #7 /var/www/html/ Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(Array, 'kernel.request', Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #8 /var/www/html/ Symfony\Component\EventDispatcher\EventDispatcher->dispatch('kernel.request', Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #9 /var/www/html/ Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #10 /var/www/html/ Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #11 /var/www/html/ Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #12 /var/www/html/ Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #13 /var/www/html/ Symfony\Component\HttpKernel\Kernel->handle(Object(Symfony\Component\HttpFoundation\Request)) #14 {main}

Lovely job.

Anyway, this was a pretty simple fix, even though there isn’t much about this on Google.

As part of this project, I needed to overwrite the default FOS User Bundle templates with my own. A pretty typical task tbh.

As it happened though, I had removed kept the FOS User Bundle error logic, but removed the translation part.

Something like this:

 {% trans_default_domain 'FOSUserBundle' %}
{% block fos_user_content %} {% if error %}
{{ error.messageKey|trans(error.messageData, 'security') }}
{% endif %}

And I had gone ahead and changed that in my template to something like this:

 {% block content %} {% if error %}
{{ error.messageKey|trans(error.messageData, 'security') }}
{% endif %} {% endblock %}

So I had removed the trans_default_domain, which in turn, was – as far as I can tell – then simply rendering out the full stack trace.

I’m not sure if FOSUserBundle catches that error, and then translates it? That seems kinda unusual to me.

Anyway, hopefully this saves someone some time, someday, some time soon 😉

How to Fix Composer: ErrorException fork failed – cannot allocate memory

If you’re trying to deploy a Symfony project – or Laravel, or pretty much anything using composer – and your deployment server is a little anemic on the memory side of things (Amazon AWS, tiny Digital Ocean droplets, even the basic Linode offerings), then you may well hit an issue when you run composer update during your deploy.

There’s quite a long github issue thread about it, and another one on Stack Overflow.

Anyway, after much frustration, here is my fix – which works for me, hopefully it will work for you too.

This assumes you are developing locally and then deploying to prod using git, which I highly advise. But it will work for any type of deploy if you follow the steps and tweak accordingly.

  1. Do a composer update on your dev box
  2. Commit the updated composer.lock file
  3. Push the commit with the lock file to your prod server (or wherever you’re getting that error)
  4. From the prod server (or wherever), delete your composer cache (rm -rf ~/.composer)
  5. From the prod server (or wherever), delete your vendor folder (rm -rf vendor)
  6. From the prod server (or wherever), run composer install

So, whilst the above is the high level overview, here’s how I did it irl.

  1. Using ssh, I connected to my development virtual machine (VMWare), where from the Symfony root dir (/var/www/html/, I ran composer update
  2. Wait a while, whilst number 1 finishes.
  3. From my local machine, download the newly updated composer.lock file. Git sees this as a changed file, and so I can then do a git commit on the updated composer.lock file
  4. As I have already set up a git remote for my production server, I can then do a git push for the commit with the lock file to my production server.
  5. When the commit hits the server, the post-receive hook is run automatically, which does all the Symfony deploy stuff like clearing the cache, dumping assets, reinstalling vendors etc.
  6. If all this sounds great, but deploying with Git is something you’re unsure of, I highly recommend this Digital Ocean article, which makes it very easy.

    Hope it helps!

Split MySQL Column On Tabs To New Columns

Disclaimer: this is a horrible hack.

Ok, so I had a requirement to take a MySQL data set where there was a column called ‘address’ which contained an un-normalised, imported address that looked something like this:

Derby House
Lytham Road

And turn that into:

address1: Derby House
address2: Lytham Road
address3: Fulwood
address4: Preston
address5: Lancashire
address6: PR2 8JE

Ok, so that’s the plan.

Before we go any further, yes, I am fully aware this is not a great solution. For example, what if the next address only contained 5 rows – that would mean the post code ends up in address5.

That’s why I said this is a horrible hack, right at the beginning there. So don’t flame me.

Anyway, this *may* be useful to you.

UPDATE `your_table_name` SET
    `address1` = IF(
        LOCATE('\n', `address`) > 0,
        SUBSTRING(`address`, 1, LOCATE('\n', `address`) - 1),
    `address2` = IF(
        LOCATE('\n', `address`) > 0,
        SUBSTRING(`address`, LOCATE('\n', `address`) + 1 ),
    `address3` = IF(
        LOCATE('\n', `address2`) > 0,
        SUBSTRING(`adcampsite_resultsdress2`, LOCATE('\n', `address2`) + 1 ),
    `address4` = IF(
        LOCATE('\n', `address3`) > 0,
        SUBSTRING(`address3`, LOCATE('\n', `address3`) + 1 ),
    `address5` = IF(
        LOCATE('\n', `address4`) > 0,
        SUBSTRING(`address4`, LOCATE('\n', `address4`) + 1 ),
    `address6` = IF(
        LOCATE('\n', `address5`) > 0,
        SUBSTRING(`address5`, LOCATE('\n', `address5`) + 1 ),
    `address2` = IF(
        LOCATE('\n', `address1`) > 0,
        SUBSTRING(`address1`, 1, LOCATE('\n', `address1`) - 1),
    `address3` = IF(
        LOCATE('\n', `address3`) > 0,
        SUBSTRING(`address3`, 1, LOCATE('\n', `address3`) - 1),
    `address4` = IF(
        LOCATE('\n', `address4`) > 0,
        SUBSTRING(`address4`, 1, LOCATE('\n', `address4`) - 1),
    `address5` = IF(
        LOCATE('\n', `address5`) > 0,
        SUBSTRING(`address5`, 1, LOCATE('\n', `address5`) - 1),
    `address6` = IF(
        LOCATE('\n', `address6`) > 0,
        SUBSTRING(`address6`, 1, LOCATE('\n', `address6`) - 1),

What this is doing, in a nut shell, is splitting the row by new line (\n), one step at a time, then repeating the split, on the new column.

So in our case, taking the original example, the following happens:

‘address’ column:

Derby House
Lytham Road

After the first if statement, ‘address1’ becomes:

Derby House

All the other columns are blank.

After the second if statement, ‘address1’ doesn’t change, but ‘address2’ becomes:

Lytham Road

After the second if statement, ‘address1’ and ‘address2’ don’t change, but ‘address3’ becomes:


And so on, until all the columns are populated (up to address6).

Then, after this bit:

    `address6` = IF(
        LOCATE('\n', `address5`) > 0,
        SUBSTRING(`address5`, LOCATE('\n', `address5`) + 1 ),

The code ‘loops’ back through and removes anything in each column after the first new line (\n).

There is likely a more elegant solution to this problem. But, in my case, finding that solution wasn’t justified as this hack achieves the desired outcome.

Hopefully it helps someone, somewhere, somehow.

Testing Sessions With Codeception

Testing sessions is a pain.

But it’s better to have pain when testing than pain when the site is live.

So test we must.

He was aiming for the bike

Ok, so as I’m all about Symfony 2, this is going to be an example of testing a Symfony 2 Service that makes use of Sessions.

First of all, we define our service so that the Symfony 2 Session (Symfony\Component\HttpFoundation\Session\Session) is injected for us.

        class: Our\BundleDir\OurBundle\Service\OurSessionManager
            - "@session"

Hoorah, nice and easy. Feel free to use whatever naming convention you like for your service. Personally I like to make it quite verbose, so it’s super easy to track down where that service lives when you return to your project in 6 months time.

If you’re wondering what other things can be injected, then this chapter of the Symfony docs is worth a read. Also, try using:

php app/console container:debug

on your command line.

So, we have our service definition. Now to make our service, and our associated test file.

The service itself:

namespace Our\BundleDir\OurBundle\Service;

use Symfony\Component\HttpFoundation\Session\SessionInterface;

class OurSessionManager
    const OUR_THING = 'our_thing';
    private $session;

    public function __construct (SessionInterface $sessionInterface)
        $this->session = $sessionInterface;
    public function setOurConstantThing($value)
        $this->session->set(self::OUR_THING, $value);

        return $this->session;

    public function getOurConstantThing()
        return $this->session->get(self::OUR_THING, '');

Your implementation can do whatever it likes. This example is deliberately convoluted to show off a few things.

Naughty, we wrote an implementation without writing some tests. Let’s fix that before we get in trouble.

class OurSessionManagerTest extends \Codeception\TestCase\Test
    private $serviceContainer;
    private $service;
    protected $codeGuy;

    protected function _before()
        $this->serviceContainer = $this->getModule('Symfony2')->container;
        $this->service = $this->serviceContainer->get('our_session_manager');

    protected function _after()

    public function testCanSetOurConstantThing()
        $session = $this->service->setOurConstantThing('my_value'); /** @var $session \Symfony\Component\HttpFoundation\Session\SessionInterface */



    public function testCanGetOurConstantThingWhenSet()


    public function testGetDefaultValueWhenAValueIsNotSet()


The third test is testing the following:

return $this->session->get(self::OUR_THING, '');

Essentially that’s saying, get me our thing, or return ” if our thing isn’t set. You’re free to return null, a default value, or whatever.

But the critical thing for testing sessions is the _after() method. This is killing off any residual session stuff, and then on each new test, starting with a blank slate – so to speak.

So, there we go. Testing sessions in codeception.


Book Review – Extending Symfony2 Web Application Framework by Sébastien Armand

[Full Disclosure: I was asked to review a copy of Extending Symfony2 Web Application Framework by Sébastien Armand, and put a review on this blog.

The review is my own, and is in no way influenced by Packt Publishing]

The Symfony framework has – in my opinion – a lack of decent third party reading material generally available. One quick search on Amazon will show you what I mean. That’s not to say that there aren’t books available, but many of them are self-published, or published on these new fangled platforms that old-timers like me aren’t aware of.

And you know what, I kind of get that. Many big publishers don’t want to, or can’t afford to take a risk on publishing a title that will, in all likelihood, only appeal to a few thousand-odd developers. So, like for many parts of Symfony 2, if you want to find the juicy bits, you have to do a little bit more than a Google search.

What’s in it for me?

Truthfully this isn’t a book for the beginner. If you want to learn more about Symfony and you are just starting out, try the official manual, or heck, my video tutorials are as good a place as any, even if I do say so myself.

Rather than me trying to explain in great depth what’s in each chapter, I’ve screen-grabbed the contents for your perusal.



The Delilah Smith Guide To Symfony

Whilst the author doesn’t come right out and say it, the book feels more like a collection of the Symfony 2 cookbook style articles, rather than a deep-dive in to each of the presented topics. And again, the chapter length is a bit of a give-away on this also.

That’s great for developers who have plenty of hands-on experience with the framework, but again, maybe not so great for advanced beginners, or early intermediates.

It is suggested that you code along as you read, and whilst that’s not always practical, being able to run the code in your head (so to speak) is hugely beneficial – but completely impractical if you don’t have that prior experience.

My other gripe with both this and the Symfony cookbook articles is that if you do get stuck, you need a base of reference (Google usually) to get a better understanding of some of the high level concepts of which the author has only scratched the surface.

This can be frustrating.

However, when learning a new framework or concept, having multiple points of reference – videos, written tutorials, checking out others code on github – is always a good idea as you will see different ways of implementing the same idea.

YAML, XML-ding-dong

Oh lordy me, I wish Sébastien had used YAML instead of XML in his examples.

The chapter I was most looking forward to – Chapter 6: Sharing Your Extensions – is a super hard to read on the Kindle with the XML dumps displaying horribly.

As I typed the code out into my IDE and could see each piece on one line instead of five or more, the whole chapter became clearer. Not good for reading on the train though.

That said, I don’t think the config can be done in YAML when sharing bundles (Configuration.php) – but do feel free to correct me if I am wrong on that one?

Altogether though, chapter 6 was super useful to me, and something I had found, shall we say, unenlightening on the Symfony website.

Isn’t this information already available for free elsewhere?

Of course. The beauty of a non-fiction title such as this is rarely that you will learn some obscure tidbit that you cannot find elsewhere. Rather, it’s the time saved by letting the author collate, refine, and re-interpret in one handy place of reference that hopefully saves you a few hours digging around the web to find by yourself.

And in that respect, I think the author has done a really good job. There’s plenty of advice from disparate blogs / websites / mailing lists that can be found here, and with helpful code samples to boot. It’s certainly not always easy to read code on a kindle, but with the code also available for separate download, I think that’s more of a problem with the current state of the Kindle than with the presentation.

Good or Bad, what’s the verdict?

On the whole I enjoyed reading this book, and learned a few things in the process.

My biggest criticism is that it’s a little on the short side for the price.

However, the fact that it was so short also ensured I actually read it, rather than being off-put as sometimes happens when I buy a six or seven hundred page monster – Core Java Fundamentals, I’m looking at you.

The tone is conversational, and at no point did I feel the chapter was too dry, tedious, or overly long, and so I never skipped ahead.

Ultimately, if you can get your company to pay for your learning materials then I would recommend you take that option first.

So tl;dr: yes, it’s a good book for intermediates onwards, but for the price it’s a little expensive considering the page count.

Extending Symfony2 Web Application Framework by Sébastien Armand is £11.89 via Packt’s official website, and on purchase you can download the book in .epub, .mobi, .pdf, and view in browser using their Packt Lib application. All formats are DRM free.

And lastly, a huge thank you to Sébastien Armand, and to Packt Publishing for asking me to review this book, I really enjoyed doing so.

Free Symfony 2.3 Tutorial Videos

If you are thinking of making the switch from Functional to Object Oriented PHP development, or have already ventured down the OOP route and tried a framework (Laravel, Cake, Yii, or similar), chances are you will have hit a few stumbling blocks or worse, given up in despair.

I remember being there.

I also remember wishing someone had come up with some video tutorials which I could watch rather than having to slog through the manuals.

Now, don’t get me wrong – you are still going to need the manual, but hopefully these videos will explain the concepts visually, which you can then use as a base of reference when you start reading further.

There are six videos up in total at the moment with more on the way. If there is a specific topic you have in mind or aren’t sure of, I would be happy to make a video for it. Just leave a comment either here, or on youtube.

Full video list