Have You Used Symfony’s Workflow Component?

This week we’ve started two new series – one taking a beginners look at Git, and another covering the awesome Symfony Workflow Component.

The Git series is a member request. I’m always open to doing member requests, so do get in touch if you have a topic in mind.

I’ve wanted to record a series on the Workflow Component since – as best I can remember – at least a couple of months before Christmas. But there were two things stopping me:

  1. Lack of actually having used it 🙂
  2. Lack of understanding where I might use it

It took a determined effort on my part to finally find time to sit down, new up a Symfony project, and get started playing around with it.

In doing this, I took at look at the demo code (more on that below), and tried to work my way backwards, but came unstuck.

Don’t get me wrong, there’s a bunch of interesting and useful things to be learned from doing this, for example the snippet of JavaScript to mark the current ‘place’ on the diagram https://github.com/lyrixx/SFLive-Paris2016-Workflow/blob/89c5a671a765896615af6173ca85cabbf9404a60/app/Resources/views/article/show.html.twig#L51. But this is the overly complex approach.

By starting with a new project and building up my knowledge incrementally, I was able to gather a momentum in learning much faster than I had initially anticipated. Isn’t this so often the case? New things seem scary and difficult when viewed as a whole, but when broken down into chunks and tackled piece by piece, suddenly things don’t seem quite so daunting.

Anyway in doing this I realised I was sitting on the solution to a problem in an app I’ve been working on for over a year now. I had this rather annoying situation whereby my app would run a cron job every minute to figure out if there was anything new to post out to social media. If there was, this would be added to RabbitMQ, which has an army of waiting workers, each designed to do one small task, and then pass on the responsibility downstream.

As part of this, the post could be in various stages – pending, posting, posted, failed, retrying – and I had managed, even in my small scale testing, to have found posts jumping about all over the shop – from pending to posted without ever posting, from pending to retrying without failing… the possibilities were annoying, and the outcome was one of frustration. I shelved my work on the app around August and vowed to return once I found a suitable solution.

In learning about the Workflow Component I was fairly sure I’d found a potential solution. I’m not saying simply adding a workflow definition solved my problems, but in doing so it did stop my entities from transitioning to invalid states. And when these transitions failed, I was able to more easily log out important information, and isolate the root cause of the problem. Actually the root cause turned out to be my lack of understanding of Rabbit MQ, but that’s a different story 🙂

Video Update

This week saw three new videos added to the site:

https://codereviewvideos.com/course/beginners-guide-to-git/video/getting-started-with-git

First up we have an introduction to Git. In this series we cover all my most frequently used commands when working with Git on a day-to-day basis.

I use Git now for every project I do, and have done for at least the last three years. I still have a client who insists on SVN, and by comparison it is nothing but pain, fear, and frustration.

Anyway, I fully appreciate that when initially beginning with Git, it is akin to learning a whole new programming language. The good news is, much like in pretty much any programming language I have ever used, even though there are often 100s (if not 1000s) of commands / functions available, for most tasks you only ever need the same few.

Git is no different.

Sure, there are a bunch of advanced ways to use Git (submodules, anybody?) but mostly it’s just about adding, removing, committing, and pushing.

In this video we cover the most commonly used basics whether working alone, or in a team. In the next video we will cover branches, which whilst incredibly helpful if you’re working alone, become even more powerful – and potentially problematic – when working in a team.

https://codereviewvideos.com/course/symfony-workflow-component-tutorial/video/workflow-component-introduction-demo

Next up is the start of a new series covering Symfony’s Workflow Component.

This is a new component available either:

  • standalone;
  • ready-to-go in Symfony 3.2 onwards;
  • or available as a third party bundle (fduch/workflow-bundle – https://github.com/fduch/workflow-bundle) if you’re still on Symfony 2.

As hinted at earlier, the Workflow Component is all about helping you manage the lifecycle / processes that your objects / entities go through as they pass through your system. Whilst that might sound a little dry / technical, the chances are you have some small, or large part of your existing and future projects that could readily benefit from using this tool.

To begin with we take a look at the rather brilliant Workflow Demo App that was created by Grégoire Pineau for his reveal of the Workflow Component at Symfony Live Paris 2016. In this video we will cover the two examples available – workflows, and state machines – and when and why you may wish to use each.

The Workflow Component brings with it a fantastic visual tool in the form of the Dumper, allowing you to output diagrams which represent the processes you’ve created via your Workflow definitions.

https://codereviewvideos.com/course/symfony-workflow-component-tutorial/video/a-simple-state-machine-example

In the previous video you got to see both workflows and state machines in action.

However, whilst seeing the power of this component is useful, to get your head around how it all fits together is somewhat easier with a more basic example.

There’s loads of interesting things covered in this video – and starting with a new Symfony application you can code along and learn as you. It really is the very best way to inwardly digest this material.

By the end of this video you will have a good understanding of:

  • how and why workflows and state machines differ
  • how workflow definitions are created
  • how to create both places and transitions, and what these terms mean
  • how to customise your marking store, and why you might want too
  • how to create your own workflow diagrams, and a potential bug you might encounter

Honestly I love the Workflow Component, and if you don’t already, hopefully after this series you will too.

Until next week, take care, and happy coding.

Chris

The Lazy Man’s Guide To Symfony Services

Late last year I created an API using Symfony 3 for a personal project, and had the intention of talking to this API via WordPress. Or more specifically, from a custom WordPress plugin. I thoroughly enjoyed building that API. It followed my usual practices of testing with Behat and PHPSpec, and I must have built about 20 or more API implementations now using Symfony 3, so development flew by at a jolly old clip.

Then, this week I had a bit of spare time. Why not, I thought, create the WordPress plugin?

You’re probably expecting a horror story. And if I’d been writing this email at any time before 11am yesterday then you wouldn’t have had one.

Everything was going smoothly. A little too smoothly, considering I have next to no recent experience with WordPress.

All I needed to do was add in a button to the visual editor which, when clicked, would show the user some info in the form of three drop down boxes.

It’s the classic wizard-y type thing: what you select in drop down #1 should filter the available options in drop down #2, and so on. Sounds like something that shouldn’t take 9 hours, right?

At this point I am sure you are thinking: “Lol, that’s WordPress for you, you newb!”

But that’s not fair on WordPress. At least, not directly. The issue I had was with tinymce, an included third party dependency of WordPress.

I won’t rant too much here but why, oh why, would re-inventing the extremely standard select box with a wide range of nested divs and buttons ever seem like a good idea? It frightens me that this code is distributed to the several tens of million (est. 74m+ with a quick Google) WordPress websites out there.

Anyway, as I say I don’t want to rant – I already lost a days worth of productivity to this, but to bring it home I cannot stress enough how lucky we are as Symfony developers to have access to such amazing documentation.

And when the docs can’t get you where you need to be, a dive into the code won’t lead to some minified, and uglified JavaScript.

And if that still doesn’t get you the answer you need, a really nice tip is to use github as a Google for code. Try and find someone else’s project who has done something identical – or very similar – which you can *ahem* borrow. Try doing that with a search like “tinymce plugin”, and behold the madness.

Video Update

This week there have been three new videos added to the site:

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/getting-started-with-jest-mocks

First up this week we started mocking things in Jest. Specifically we didn’t want to make real API calls during our tests – for many reasons – instead choosing to mock the real function that would make the calls, essentially tricking our code into thinking that nothing was out of the ordinary.

Mocking in Jest does differ slightly to how you may have mocked before, but is quite intuitive once you see it in action. Just be careful to clean up after yourself (covered in the video) unless you enjoy the unexpected 🙂

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/using-webpack-environment-variables-in-jest-tests

One thing that drives me nuts is when I read through the documentation – which if done right, usually makes things look very easy (and therefore encouraging to adopt) – only to be met by real world issues that either are completely ignored in the docs, or found only after a dive through the project’s GitHub issues register.

Now, if your project is anything other than a learning exercise, sooner or later you need to go into production. This brings one particular problem in the front-end > back-end paradigm: we likely don’t want to use the same URL for our API in production that we use in our development environment.

Of course, Webpack has us covered here, though the specific approach is not that intuitive.

But Jest doesn’t use our Webpack config. And is therefore completely unaware of our constants. Arghhhhhhh!!!!

Ok, so in this video we address this – and another problem. This should save you a ton of time if you’re following along, or building a similar project.

https://codereviewvideos.com/course/how-to-autowire-symfony-services/video/how-to-symfony-autowire

Lastly this week we look at Symfony Service autowiring.

This is perhaps the nicest feature of Symfony that I never use.

That said, it is nice to know this feature is available, and not difficult to use at all. In this video I will show you how to use autowiring, and leave you to form your own opinions as to whether you might find this useful.

10 Tips For Better Symfony Debug Logs with Monolog 

I can’t quite believe it’s over a month already since Christmas day. Although I only need to step outside for a few moments to wish it was Summer already. I’m much happier coding in my shorts and t-shirt.

A number of people have asked for a suggested watching order / learning track, and with 50 courses to choose from, I can totally understand it can be hard knowing where to start. With this in mind, I’ve added a Learning Tracks page to the site.

This week saw three new videos added to the site.

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest-happy-path

Firstly we cover testing JavaScript’s Fetch, the nicer replacement to XMLHttpRequest. It baffles me why XML is uppercase, but Http is title cased. Anyway, fetch is nice to use, but testing can still be a little tricky.

To begin with, we cover the happy path, which gets our setup code out of the way. Seeing how things work when the everything is right in the world is a great way to start. But of course, once real users start tinkering with our systems, inevitably they will find new and baffling ways to destroy our good intentions. Which is why…

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest-unhappy-paths

We also need to cover the “unhappy paths”. And in this case, testing that our code throws the expected exceptions is a little trickier than you might expect. It’s one of those problems that you might estimate at taking you a morning, but end up losing two days too – never fun explaining that in the daily stand up.

Fortunately help is at hand, and we will use a small snippet of code to ensure testing when things go wrong is that much easier.

When it comes to tracking down errors, of course it’s not just the client side that can go wrong. If you’ve worked with Symfony beyond the most basic of applications then more than likely you will have needed to log out additional information to help you debug. Monolog is the fantastic out-of-the-box logging solution in Symfony, and so…

https://codereviewvideos.com/course/log-log-it-s-better-than-bad-it-s-good/video/10-tips-for-a-better-symfony-debug-log 

In this video we look at 10 ways to improve your Symfony debug log output by making use of a variety of options and techniques that Monolog gives to us.

We start off with the basics here, but quickly cover the handler stack – including the rather brilliantly named fingers_crossed  handler, which you will have seen in config_prod.yml  – then onto channels, logging from console commands, and also how to log out to Graylog.

This video will be free to watch until next Friday, so be sure to set aside 10 minutes for this one.

Lastly, did you know you can keep track of the latest videos via an RSS reader? I have a full feed available to ensure you never miss a video.

Until next week, take care, and happy coding.

Chris

Grab a Backlink

I can’t quite believe it’s Friday again already. I mean, it’s nice and all because of the weekend, but I never feel like I’ve achieved quite as much as I had planned.

This week I saw a really interesting ‘thread’ (is that the right word?) on Twitter from the Laravel community showcasing interesting projects being worked on:

(credit where it’s due, I found this via @davedevelopment, a really talented and knowledgeable dev who I would highly recommend you follow, if you don’t already)

Anyway, I think we should share our own projects in the same way. You already know mine – CodeReviewVideos – but I’d love for you to share yours. If you want to get in touch, reply here, or any of the other numerous ways to get in touch, and I will share any I do get in next weeks mail out, plus you will get a backlink from the blog. I can’t promise heaps of traffic, but as Tesco say, every little helps.

There have been three new videos added to the site this week:

https://codereviewvideos.com/course/beginner-s-guide-to-symfony-3-forms/video/snake-case-on-your-forms-camel-case-on-your-entities

I was recently on a piece of client work whereby an API had been created, and somewhere along the lines the business requirements had dictated a change in JSON output from camelCase to snake_case.

Now, there’s a couple of points that need to be addressed here – firstly you’ve got your output (GET requests) which is the obvious one. But if you’re accepting input (POST, PUT, PATCH) then you need to ensure you update the associated form fields, and that’s a breaking change for API consumers.

Anyway, in this particular case the externally visible change had already been made. But to make the change, the devs had decided to fudge all the class properties from camelCase to snake_case, which in turn, caused some additional, seemingly unrelated problems. Most of the time when you circumvent the way Symfony expects you to work, you’re going to open an entire pallet of cans of worms that should make you sit up and think – hey, we cannot be the first people who want to do this. What’s the right way to do it?

In this video we cover the simple way to do this that ensures your view concerns don’t need to affect your model concerns. And if you’re in a similar position and need to handle the GET / read side of things, one easy way is to use JMS Serializer’s SerializedName annotation.

https://codereviewvideos.com/course/phpstorm-shortcuts/video/become-a-better-developer-with-php-inspections-ea-extended

If you aren’t using PHPStorm then I would strongly advise you to give it a try. For Symfony there is an excellent plugin – the Symfony plugin being the most essential.

However, regardless of whether you “do” Symfony, Laravel, one of Zend’s offerings, vanilla PHP, WordPress, Magento… (the list goes on), then your code quality stands to be improved by using the PHP Inspections EA Extended plugin.

Honestly, this plugin is fantastic. Unless you have the cold, artificial heart of a PHP codebot, I am confident this plugin will find at least one ‘problem’ in your code that could be improved. My favourite feature is how it finds code that may throw exceptions somewhere down your stack, which you may very well not be handling – or at the very least, not documenting.

This one is well worth the 30 seconds it takes to install, and I cannot recommend it enough.

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-authsaga-unhappy-paths

Lastly this week we covered testing the “unhappy path” through the AuthSaga in our React / Redux / Redux Saga > Symfony 3 API project.

In this video we look at how we can quickly test a couple of problem areas:

1. Ensuring our saga throws when a call to api.login fails, and;
2. Ensuring our saga throws if the api.login response doesn’t contain a token in the response body.

As a side note this week I’ve been playing with JavaScript’s MobX as an alternative approach to Redux. Whilst I like it, I still think Redux Saga is the easiest way to write code that is extremely testable, which means you gain that much higher level of confidence that it will work now, and in the future even when you inevitably change stuff.

Until next week, take care, and happy coding.

Chris

Have You Ever Used A Symfony Compiler Pass?

It’s been JavaScript, JavaScript, JavaScript for the past few weeks, so this week I thought I’d vary things up a little and, heck, cover a little Symfony 🙂

Yes, two new – dare I say – useful videos were added to CodeReviewVideos this week.

Lets go ahead and jump right into it.

First up we venture into the wonderful – and scary sounding – world of Compiler Passes. Now, this is one of those Symfony things that is really useful, but also something you’re unlikely to try until you’ve seen it working before. Ahh, the old catch 22. Not so bad if you work in a huge team of devs who all share knowledge (or you are particularly good at reverse engineering), but if you’re a lone wolf, or part of a smaller, less experienced team, things like this may completely pass you by.

To begin with, we start with a code smell that I saw recently when working with a client. This problematic code is fairly common, and isn’t specific to Symfony projects. You may even have it in your own projects:

Controller bloat.

This particularly issue starts off with an if  / else , which turns into an if  / elseif  / else , and within a few further iterations you’ve got this nasty conditional dominating the method. Actually in the code I was looking at, this was a common theme throughout multiple controllers, and multiple actions in each controller. It’s things like this that make people believe Symfony is hard, when in reality, this problem would follow you if you switched to Laravel, or Zend, or Slim, or any other.

We’ll use an example of having to convert an array of data into a variety of formats – CSV, XML, YAML, and so on.

To begin with, these various conversion strategies live inside our controller action.

In the first video we cover a simple way to start refactoring this code:

https://codereviewvideos.com/course/symfony-compiler-pass-example/video/extract-extract-extract

At this stage all we are doing is extracting the problem code from the controller. This is really easy to do, and can immediately start to reduce duplication, and increase code re-use.

Unfortunately this doesn’t actually solve the tight coupling problem. But sometimes, you know what? You don’t need too. Over engineered code can be just as painful to work with as sloppy code. It’s just a different kind of pain.

Anyway, on larger systems simply extracting code out like this may not give you the flexibility you need. For that we can use a technique that third party bundles use:

https://codereviewvideos.com/course/symfony-compiler-pass-example/video/introducing-the-compiler-pass

In this video we cover how to use a Symfony Compiler Pass to decouple the Conversion service we’ve created from the various conversion strategies (e.g. convert to YAML, convert to JSON, and so on).

Let’s imagine that you wanted to create a Symfony Bundle that you could then share with the world in order to help others who might need to convert arrays in the future. Whilst you might provide a variety of implementations out of the box – ConvertToJSON, ConvertToXML, and so on – you don’t want to be solely responsible for adding every possible implementation in the future.

Instead, you could allow users of your library to implement the expected interface, and then use a Symfony service Tag that tells your Conversion service to also include this custom converter that your library user has created.

There’s loads of uses for this approach, and honestly it’s easier to do than you might think. Much like a lot of Symfony concepts, actually 🙂

All of this weeks videos are free to watch, though I will be making the Compiler Pass video a Members Only video at the end of this month.

Until next week, take care and happy coding

Chris