 I'm Barney, Barney Hanlon and I was asked before we kicked off what's that from and so I'll just clarify that I am a massive Battlestar Galactica fan. If you don't know the series, well no questions from you until you answer that. So firstly, today's a very special day for me and this is not only my first ever talk at the conference but it's my 10th conference which when I look back actually feels really amazing and I'd like to thank PHP Southwest especially because last month they invited me up to give this talk so I got a lot of really good positive feedback from them and they were lovely and if you want to do speaking and come up here I don't think you'll need to do nine conferences before you attempt it. But I would recommend that you go to PHP Bristol and practice your talk and then come up here. So what do I do? Well the sharp-eyed amongst you might have noticed this little logo on here and as my manager is in front there so I work for World First. We are foreign currency and payment specialists so transferring euros to dollars, pounds, whatever you want around the world. There's 60 of us in IT, developers, DevOps, infrastructure. Oh I forgot QAs, they will kill me. None of my stories are getting through now. Guess what, probably like a lot of people here, we're hiring. So I work as a developer specialising in mentoring internally on better practices, improving code and so forth. And my team love me, they've shortened how they've described me as the Dementor. So anyhow, it's a great company to work for but it's not without problems. We had huge growth which led to developers sticky taping on more and more to a monolith. And then we've obviously identified that and we start to try and solve that. But finance, fintech is a rapidly changing market. There's a lot of deregulation happening, a lot of new products out there and we have to be competitive or beat our competition as well. On top of the changes in the regulations, there's also needs to be more compliant, be aware of security changes and when you have a monolith that becomes obviously very heavy to make any changes, so refactor all the things. So we started coming up with some solutions in 2016 towards this. Start moving with a domain driven design approach, moving more to micro-ish services and adopting TDD and BDD everywhere. I don't think that's groundbreaking by any means. I think most people have tried that or are doing that themselves. And it's not the answer to everything, we still have some problems. With new products comes a lot of changes in the domain logic. We adopted the Spotify model. Who is familiar with the Spotify model? A few hands. Actually not that many hands. Hands up if you hate audience participation. Okay. So we started to split up the squads and give them more independence but what that starts leading to is a fracturing in frameworks, a lot more libraries being used as different squads go with a particular approach. And that's great but it also means that you're having to learn a new framework if you move squad. It also means that because the squads are sort of working independently and choosing a lot of ways to do stuff themselves, we start having like a zillion internal endpoints for our APIs. Which is okay but then you start having to just learn another squad to Jason. This is perhaps my favorite ever recruiter's email to me. Unfortunately it does become a thing that you become a Jason programmer. So we started to think about this last year and how are you going to solve this. So quoting the great philosopher Vanilla Ice, he then went on to say that he was back for the brand new invention but we can leave that. But some of the things that he would have sung about as well is that we're not going to refactor all of these working APIs just so that they have the same framework. It doesn't give us anything. There's tests. If somebody's using Lumin or Laravel because they're masochistic or they're using Symphony or whatever. I've mentioned that specifically because of a chat last night. But it doesn't matter what your framework is. If it's working, don't replace it. There is no need for a company-wide framework. But we do need to handle away to all of these different changes and how we're going to get things to work in a common kind of way. And we need to plug in this new functionality. We've got new products and we need to, you know, slot them in to these APIs. So we started to think about how we're going to do this. And we came up with a couple of solutions. So we're now going to use command buses to tell our domain that we want to do something. Then we're going to use event buses to inform our domain that something has been done. And then we're going to use action domain responder pattern to control the interaction between the framework and the command bus. So it's really now about how we be commanding. OK. Problem is, the term is overloaded. If you start thinking about what a command is, if you type command PHP into Google, that would probably bring back a lot of results, none of which would be very useful to you. Gang of four talk about the command pattern. OK. That's one. Domain driven design refers to commands within business processes when you do domain mapping. And then, of course, another popular one which was mentioned in the talk just before mine, CQRS. We'll start with CQRS because whilst all of these patterns are different, they play nicely together and they're not mutually exclusive. So, CQRS is command query responsibility segregation. And the heart of it is this notion that you can use a different model to update information than a model you use to read information. If you start, if you come from using doctrine, early doctrine usage, you'd probably see that you have like one entity that does everything. You know, it has a column. It's basically mapping to every single column in your tables or related tables. If you have a user table with 30 bits of information, that entity has 30 private variables or protective variables in the case of doctrine. But you're only going to be using a small subset of those during certain operations. But you've now created this massive one that you have to test and use and make sure it's working. It's not necessarily helpful. It's also not being a single responsibility. It's now everything to do with user. Well, when I'm registering a user, they're not a user. They're a customer or they're a client. I only need maybe an email address and password. Why do I have all of this stuff about their account number? Now, that could be that you just go, oh well, normalise your database. Potentially. But you're already in this place. The thing is to have smaller models that are more related to how you use your app rather than just one supermodel. And along comes a command pattern. Now, I couldn't find my gang of four book to look up their definition, so I want on the ever-reliable Wikipedia. So it's saying, in object-oriented programming, the command pattern is a behavioural design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method, and values of the method parameters. OK, fair enough. That's a good dictionary description, but in a more helpful kind of way, they're very simple data transfer objects. They don't know how they're going to be used. But only enough information so that they can be used. So enough to complete the command, basically. And if you have this command that you've created, and you have another command that's got the same values, it is equal. Simple value object. I have some code now to show you. The launch viper's command. So it's very simple. We've got a constructor, some private variables. It takes the launch time in and creates it as an immutable. And it's got some simple getters. Nothing really useful about it in that sense. Apart from its name is quite fixed. It's launch viper's command. It's clear what it does, even if it doesn't know what it's going to do. So if you look at command buses, so there's less on this. The first proper reference I came across this was on the League of Extraordinary Packages. It's when you combine the command pattern with the service layer. Its job is to take a command object, which describes what the user wants to do, and match it to a handler which executes it. This can help structure your code neatly. I firmly believe, after a year of using it, on that last sentence, it does make your code very neat. There are two libraries that I'm familiar with. I was reminded of one just before this talk, is Simple Bus, which I have excluded from this, which is a bit of a shame. But the one that we'll be using today is Tactician, which is by the League. And another one is called Broadway. Now Broadway is very interesting, because it's actually full event sourcing, which we'll touch on the periphery of this talk. I've used Broadway, and I like it. I think everybody can help by giving them some pull requests for some better documentation, because they have some good examples, but it's not the easiest thing to immediately jump into. But I would certainly recommend it if you want to save your events to a database. And so here's a simple handler. See, we're going to use the Deck Crew Service. And so this is the Launch Vipers Handler. In the case of Out of the Box, Tactician will take a command, so it's called Launch Vipers Command. This is called the Launch Vipers Handler. It will automatically map for two. And we have one method, Handle, which takes in the command, and it's going to take the Deck Crew Service and tell it to get the birds in the air for a given Battlestar from a flight pod with that squadron. As you can see, it's getting everything that it needs from the command. It doesn't need to know about anything else apart from the service that was injected into its constructor. And then tying this all together, there's a lot of code there, actually. Gosh, make a note of that. So we're going to create Tirl's Deck Gang as the Deck Crew Service. We're going to set up the handler with it, and then we're going to use Tactician's Quick Start method, and we just say, OK, to make sure that we're explicit about it, the command of that class will go to that handler. Simple map. Then we create a command, and then we say, off you go, handle it command bus. We don't need to know much about the command bus itself. It's a simple enough map for us and gives us a point of abstraction. Within Tactician, you can also, instead of creating a handler like this, you can also use a PSR11 container so that you can load your handlers in a lazy... lazy load them based on what command comes in. So let's talk about event buses. So that's command buses. They're fairly simple. The emission is the other side of it. And PHP has certainly had event bus-like structures for some time. Probably the first one that I came across was Drupal and its hook system. It's a very simple pub subsystem before there were real events and listeners. Zen framework then took it a little bit further with pre-dispatch and post-dispatch, and although it didn't provide as many hooks as Drupal, what it did bring was prioritisation, which is an important aspect to event listening. Then, somebody wrote SPL Observer, which is there, but I haven't really seen a lot of people use. And then probably the most popular one is the Symphony Event Dispatch, which you see regularly being used within, I think even PHP spec and BHAT use it. PHP unit might use a variation of it. I can't remember. There is another one coming soon, which I'm hoping to finish this year, which I've written it three times because I keep coming up with different ideas. The one thing that I'm trying to improve is that all of the event dispatchers, and I think the term dispatcher has come from their history within Zen framework or Symphony as being the backbone of an MVC system, League has an event system, they call it Emission, which in some way sort of correctly helps split the mindset because otherwise we're not really using events inside MVC in the right way, I feel. We should call them Emission. We're saying, hey, something has happened and bounce when I finally finish it has a cue so that, because at the moment all of the systems out there only accept one event at the time. Which is breaks how you want the application to flow sometimes. So a very simple event. I rewatched the miniseries two nights ago to make sure I got this correct. Radiological alarm was triggered event. So we have an inbound Cylon Raider and it has a number of nukes that it's going to launch. And again, we're doing very simple getters. Now we want a listener for this. Now if it's a Symphony listener then it's just a simple callable. So we're going to use invoke on it. And clearly what we want is we don't want to be hit by nukes. So we're going to have the listener if there are inbound nukes. We're going to send our viper to intercept the nukes. And we'll see if we're successful later on. But now we'll set it up in some ways. It's very similar to how we set up the command bus. As you can see, again, we say to the event bus, in this case it's the Symphony event dispatcher. We're going to add a listener and we're going to say, okay, you're going to listen on this event. And then we dispatch the event to the event bus. And hopefully the listener will act and stop the nukes. If you compare them, they're pretty simple, pretty similar, but there are some differences. They're both very simple DTOs. I like to think of them as beautifully dumb. There is almost nothing to test on an event or a command. Apart from I've put something in your constructor, can I get that thing out? They should be self-validating, however. You should not be able to create a command or an event within valid data. There should be something within its constructor that says, hey, in some cases that might be just as simple as type hinting, but it might be that it does a little bit more. The main difference is that commands know or have a one-to-one relationship with a single handler, whereas events don't have that relationship with listeners. They may have a very simple example here. We have one event with one listener, but there could be n number of listeners and the names mean nothing at that point. They also don't know anything about the mechanism. There was nothing in there that said, you're coming from the command line or HTTP or the end of a queue. So their world, the world of a handler and the world of a listener is basically whatever you put inside the command or the event, which makes them extremely easy to test because you're in full control of that command or that event. The command bus abstracts away the direct link between the command and the handler, and you switch out stuff, but it's still one-to-one. The event bus' role is to manage a many-to-many relationship because there's nothing stopping a listener listening on n number of events or vice versa. Okay, that's commands and events, but how do we use them or what is the advantage of them? We'll talk briefly about hexagonal architecture. It's also known as ports and adapters. Are you familiar with hexagonal architecture? Some raised hands. Okay, not enough raised hands, so we will go through this. So allow an application to be driven equally by users, programmes, automated tests or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases. This is by Cockburn, who I believe, well, he's certainly the one that comes up highest on Google for knowing about this. This diagram, I'm sure, if you've seen hexagonal architecture before, you'll be aware of this, but we can see that we have adapters around the edge, so we have UI, test agent integrations, and we even have it at the other end with our mock database or a real database. So we're in control, and then our application is in the centre of that. The nice thing is that the application is beautifully ignorant of the nature of the input device. So what, from a PHP perspective, are those adapters? Well, HTTP. It could be Laravel, Lumen, Symfony, and even Drupal if you're using Whiskey. Or it could be the command line if you're using Symfony Console or Artisan. It could be just a QListener, or it could be your testing framework. These are all the inputs, and they should be treated as adapters. So when you're using the command pattern, here's a diagram that basically shows that you can think of this as your HTTP adapter, and that could be an entire Symfony Flex stack or just a slim micro framework. It doesn't really matter. The important thing is that your domain logic is way over there. It doesn't know about it, and you use the command bus to communicate with it. Now, why bother? You might think, well, it's just another level of abstraction. What do I gain from it? Can anybody say which CEO said this? Take as long as you need to understand your domain logic before building a working product. Your product can change, your logic shouldn't. Anyone? No? No CEO has ever said... This. When it comes to writing domain logic, the reality is key people are unavailable. If you go to the head of compliance and you say, can I speak to you about how are we compliant in Singapore? And they say, sure, I've got a slot in my diary in five weeks' time for half an hour. Can you delegate that to somebody else? Yeah, they'll be available in three weeks. OK. Well, it doesn't mean that we can't write any code to do with compliance for three weeks. Or could we do the rest of the stuff? You've got to get your app towards the finish line. You need points where you can just say, we'll come back to this. The reality is that that's just how it's going to be. You also can't mock something unless you know what it is. You need to know a name. You need to know a method that you're going to say, ah, it will return true or it will return false or whatever it might be. So let's take a look at an app without a bus. This is Launch Vipers Controller. So we're going to use the... We'll have an index action. And we're reading from a server request. We're going to get the type of the viper. We're going to set up a battle star. It's name and number, which I assume would be 75. We're going to read what flight pod it is. We're going to create the launch time as now or... No, sorry, some point in the future. And then we're going to go to the deck crew and say, get the birds in the air. And then we've got some catching for if any of that data is invalid. The thing with this, though, is I'm now doing the same with my console command. Let's say that I want to be able to do this from two sources. So I'm doing the same sort of stuff now, but I'm also then going down to the deck crew and saying, get the birds in the air. OK, this works. But there are some downsides. Apart from the obvious duplication, what's happening now is we knew some things. We knew that we were going to use a deck crew service. And we knew that the deck crew service had a method on it. So we were already done a little bit of exploring of our domain. OK. But if we don't know anything upfront, then we're having to wait to get at least that bit of information. OK, that's great. If you know a little bit about your domain, perfect. If you have an unexplored domain, then here's the command controller. We know that there is some functionality that launches vipers. We don't know that it's anything to do with the deck crew because we haven't interviewed the crew and gone, hey, how do you actually launch a viper? But we know that we can see that vipers clearly are launched and we can see that clearly they happen in result of something. So in this case, we can say, well, there is a command. And we know some bits of data that we collect. Another example of this would be registration. How do we register users? Well, we know that we collect email and password because that's on every wireframe. Where are we going to save it? How do we save it? Do we tell compliance and so forth? We don't know yet. We can defer knowing that. So instead, though, we do know that there is a command that we're going to issue. And we're going to take the information from the request. We dump it onto the command bus. Now, the advantage of that is you're turning the controller back into just knowing about HTTP. It knows about one command. But really what it's doing is going, hey, I'm going to interrogate this request and use the data within it. You're in control of the command bus. So it's nice and easy to mock it. You can say, hey, that command bus through an exception. Or did the command bus just go, yep, good job. Nice and easy breakpoint for your tests. So you don't need to have any of the services. If you go and you had to write that back and you'd started with services, if something new came in, you would have to go back into every single controller that did it and change it over. Which means you have to run your tests again, build. Maybe that's minor, but it's not great. We just did one single service. If we did that for three or four services, we're doing that over and over and over again. The command bus allows us to have it all in a handler away from our code. So the other advantage is, if you're doing front-end work is, you can just say, okay, well now we can design this front-end. We can have the 404 page, or we can have success. We can just assume that the command handler appropriately behaves, and then we can go back and solve that later. So this application flow, it's not only within the teams that will first use it, we call this the do-done cycle. So basically either your console commander or your controller acts as your adapter, and then fires a command. Do something, and just hands it to the command bus. Command bus then says, okay, this is the correct command handler to deal with this command. Then at that point, the handler will always have within it an event bus and say, I've done something. That goes to the event bus, and then that may then generate more stuff itself. So here we are. We've got the commenced FTL jump handler. So we're going to spool up. We're going to handle the commenced FTL jump, and we're going to jump the battle style. We have some coordinates that come out of it. And we go, we'll verify this with the navigation computer. And if it's successful, we'll fire an event saying jump was successful. If not, we'll fire a jump was off course event. So then on the other side, we have a listener who's going, oh right, okay, I'm listening for a bad jump event. When that happens, I'm going to take time to calculate as a plot device the new coordinates because they will fill several episodes with bad jumps. And then this is another listener that says, okay, I'm going to handle the replot of the FTL jump command. I've actually just gone, the listener in this case doesn't do anything itself. It just uses the command bus itself. So you only have writing doing in command handlers. Your listeners then don't even do anything. They just appropriately generate a new command themselves. So this leads to this pattern where you can go, okay, a command will fire an event, which then, because there are maybe three, four listeners listening for that event, generate three commands themselves. Those then fire events. And then of course, there may not be anything listening on two of those events. They might just be you're firing them, but you're logging them all, you know, to know that your application did something. And then one of those events is important. And so that then runs three commands and they fire events on and on and on. So with this model, we use action domain responder, which is a pattern that I first heard about reading through the SLIM framework documentation. There's a little bit in there. It describes it as a web-specific refinement of the MVC pattern and is like more suited to the closure-based micro frameworks. If you want to read up on it directly rather than just through the SLIM documentation, there is the link to it. It's quite a useful pattern that the important stuff from it is MVC model view controller. Do we really have views anymore in the same sense? Do we have models like that in the same way? Whereas ADR talks about actions and it uses actions in the sense of the SLIM documentation talks about invocable callables. You just set up a little function and off you go. The domain, well, we've talked about domain logic in the sense of hexagonal architecture. A responder, with views being quite clever, you have conversations with front-end devs that don't dismiss the presentation logic of an application. There's important stuff going on in there. A lot of the complexity in JavaScript frameworks like Flux, which they're clever, but let's not get around. They are more complex for the first-time user of it than we would like. There is some cunning going into our presentation logic. The responder is effectively handling all of that. The nice thing is that by having a separate responder you can have responders specific to the mechanism. You can have an HTTP responder or a console responder or for a queue you might not say anything apart from, hey, Synac, yeah, good job, this happened. You're not using a view. It could be multiple views. Your idea of what a view is in MVC is probably going to be more complex than the examples that you see in a lot of online documentation. You will want that complexity and you will want a responder to handle that complexity. Taking ADR further, the easiest way to describe this is using the commands in a useful way to cause this cascade of events. In comes a request. Now we have an action. The action is probably... We're going to use slim for this example, I think. All we're going to do is set up at forward slash that there is some index action and we'll run it. Fine, it doesn't really do much, but it's going to fire off a command to the command bus. Here we go. This is moving away from Battlestar because I was running out of episodes to watch. This is check balance. It's made up. This is not real code. It's okay. It's okay, boss. We throw into the constructor of it a command bus interface and a responder interface. In this case, we are certainly dealing with HTTP, so it's an HTTP responder interface. Again, it needs to be just a simple invocable, so we're going to take in the request. We're going to pull apart a UUID from the header and say, okay, there's a user. Then we're just going to create a new check user balance command with that user ID and give it to the command bus. Nice and simple. Now we need a handler. The handler is going to talk to a service. Or multiple services. It doesn't really matter at this point. Certainly, from the point of view of your action, it doesn't care. It's way over there. This is your real domain logic here. This is the bit where you actually care about and the bit that you're going to be talking to your stakeholders about. Here we go. This is a simple check user balance handler. Ask an authorization service if they're authorized with that user ID. I can guarantee our security model is a lot tighter than this. Just in case you're worried. We go, okay, yeah, you're authorized. You can now see a balance. Let's emit onto the event bus a new user balance was checked event. We're going to give it the balance for that user. That event is now coming out. What is that? It's pretty simple. Again, it has the actual balance. It has the user ID, simple getters. That's now going on to an event bus. From the event bus, it's going to go to any number of listeners. At this point, you can probably see where this is going. We're going to listen and we go, user balance was checked. This has a balance responder inside it. In this case, the balance responder and the HTTP responder interface are one and the same class. One cares about, hey, I'm for HTTP. The other interface cares that it can accept a user's balance. We're just going to say, hey, responder, update the user balance. In reality, what's going to happen is that could be very complex. That could be a whole twig templating system inside there going, okay, well, if the user's balance is higher than 1,000, we give them a gold star. It doesn't matter what it is. It could be anything you want on there. Or there could be things like, you've got a negative balance and we use this style sheet. Which is not appropriate for an API or a command line. It is appropriate though for when you're looking at the site over HTTP. So the balance responder, it takes care of that. In fact, if you were testing this via CLI, you would just get back, I think you would use writeLN and just say, hey, here's the user balance. But it would accept the same parameters. So, okay, so now the listener's updated the responder. And now we get a response back. Nice and simple. I hope so anyway. So in this example here, we're taking this and once we've done all of this, we go this responder response, which in this case returns a response interface. The domain doesn't know about any of that. Didn't care or isn't aware in any way that this is to do with HTTP. I know it's a PSR7 responder. Doesn't know any of that. It's just that these two are the same linked object. So it's nice and easy for us to switch out the action responder pair for any adapter. If you're doing testing, for example, we just have it. Well, you're not interested actually in the output, generally speaking. You're not going to go, well, is the style sheet looking appropriate or whatever like that. What you want to see is does that responder have the data in it that the cycle of work from all of those listeners and events, does it actually do what it's supposed to do? So responders can be as smart or as dumb as you like in this pattern. One of the things that you can do is because you're listening, you have n number of listeners populating a responder. So you can start getting into multiple events, iterating over a responder and building it up. So if a user has logged in or a user is authorised, well, I'm a responder that says, welcome Barney. So all I do is I'm just going to tell the responder, hey, welcome the user or yes, they're logged in. The responder's role then is go, well, I know that the heading on this page will have my name on it or the customer name on it. But you don't care about that for the CLI or maybe you do but in a completely different way. So they can be smart and they can be built up over time. Now because your world when you're moving through your app is just commands and events, these are really small. So it fits well with CQRS. Going back to when we were talking about how the patterns fit together nicely or at least are not mutually exclusive, you can literally write for a lot of things on your domain map when you're going through and going, all right, we're going to do domain-driven design and say this is a command. Have it literally as code and say this is a command, register this user, check this balance, move this money to here and actually use that terminology so you're doing tell-down tasks within your system. So here inside the balance responder, in this case, I'm taking a response interface. Response interface, as you probably know, is immutable. So in this case, we're just going to add a header to it. We'll just say it's an API. It's just going to respond back with your balance in the response header. It could just as well be any of the other types I mentioned before. The important thing is that because you're moving through your application with self-validating DTOs, these commands and events, you don't need to wait for a response from your command bus or you shouldn't get anything back from your command bus. Instead, you're just going, well, if I form this command and I gave it to the command bus and I want to use that data here and now, it must be valid because the command bus didn't throw a big wobbly or the event bus didn't throw an exception. Things must be working. So now I've created a user ID like a UUID. I've got that to hand. So that UUID must be valid. I can just respond directly. If I don't want to use a responder, I can just go directly back and say, here's your user ID, well done. So it does sound complex and I have some caveats. I don't actually have caveats. I really like the pattern. So this is my first talk and I've run it a little bit quicker than I expected. So I'd like to say thank you very much.