Writing SOAP Web Service Consumers in PHP

Recently I’ve had to interact with a number of SOAP web services, and I’ve come up with some techniques to help build good SOAP web service consumers.

The two most important goals when building a SOAP consumer is for the code to be maintainable and testable.

Dark Beginnings

A natural first approach is to write one class that handles everything necessary to interact with the web service:

What we’ve written above is difficult to test because we’re constructing the SoapClient ourselves. Testing any methods on the consumer would mean making a real call to the web service.

We can do better:

By having the consumer declare outright what it requires to work (an instance of a client) we’re now able to construct the consumer with mock instances of the SoapClient where we can fake real calls to the web service.

Bonus: the consumer is no longer responsible for constructing a SoapClient object with the correct credentials. It’s always a good sign to reduce a class’s responsibilities.

Writing a Test

Now that we have a way to inject a client into our consumer, let’s use Mockery to fake a web service call:

Since PHP’s SoapClient returns a SimpleXml  object from a web service method call, that’s what we’ll have our mock object return too – except we’ll use our predefined XML snippet in order to control our testing environment.

We’re now free to test the response as we sit fit!

Avoiding a 4000 Line Long Consumer Class

As you write more and more code to consume the methods of the web service, your class will quickly grow long. This will happen especially quickly if there is any complex logic associated with formatting web service method requests and responses.

The approach I use to keep classes short is to write one class per web service method. Here’s how:

The refactored consumer class now looks for a class in the App\Methods\* namespace with the same name as the method being called. If found, it will create an instance of the class, and delegate to it.

In our example, a call to $consumer->getBooks() would internally be routed to another class called App\Methods\GetBooks .

No matter how many methods we need to consume, our consumer class will never get any bigger!

Bonus: our consumer class now conforms to the Open and Closed principle.

Here’s what our App\Methods\GetBooks class looks like:

Caching Calls

A common optimization technique is to cache web service calls. With a small tweak to our consumer, we can allow our method classes to be responsible for their own caching:

Whenever a method class implements the App\Cacheable interface, the cache method will be called instead. If using Laravel, this could look like the below:

Logging Calls

Debugging will be infinitely easier if all your web service calls are logged. Since we’re injecting the SoapClient into our consumer, we can write a simple decorator to log all web service calls:

For the request to be logged correctly, we’ll need to enable tracing when configuring our SoapClient:

Of course, we can configure Laravel’s Container to correctly build our consumer class whenever we request it, by writing the following code in a service provider:


Dealing with SOAP web services can be a messy business. Use and improve upon the techniques written here to make the process a little bit more pleasant.

Happy coding!

Copying Font Awesome Fonts with Laravel Elixir

For some reason, I always have trouble setting up Font Awesome (quickly) with Laravel & Elixir.

It’s three easy steps.

Pull in font-awesome with npm or yarn

Import Font Awesome’s stylesheets in your app.scss file

Copy Font Awesome’s font files to your public directory

Configure Elixir to do this automatically for you in your gulpfile:

This last step is the one that I mix up, specifically the  *.* .

Hopefully this will help someone like me!

The Perfect Staging Environment

I’ve recently created a staging environment that I’m proud of, and I’d like to share it with you.

I wanted my staging environment to accomplish two things:

  • Always show the latest version of the project
  • Be automatically populated with dummy data

The Staging Server

Accomplishing the above is easy with Forge and Laravel. The first step in setting up your staging server is simply to enable “Quick Deploy” in your app settings page. Any time a specified branch in your git repository is pushed to, Forge will run the deployment script.

Screen Shot 2016-11-19 at 15.36.56

Easy. The deployment script is all that remains to configure the staging server. This is what mine looks like:

The line to take note of is the last one. Here we’re telling Laravel to rollback all the migrations before running them all on an empty database. Finally, the  --seed  flag fills our database with dummy data.

The Application

To enable our staging server set up to be so simple, we need to build our application in a particular way. Luckily, Laravel provides all the tools necessary to do this.

The crux of it is all in the testing environment, and by following the below two rules, you’ll allow yourself to easily create a modern staging server:

  • Build your database as part of your tests
  • Don’t rely on real data in your tests

When starting a new Laravel project, one of the first things I do is configure PHPUnit to use an in-memory SQLite database – it’s trivial, add the following lines to the  php  block in your phpunit.xml  configuration file:

Next, in my test classes that require database access, I ensure to pull in the DatabaseMigrations  trait provided by Laravel:

The trait ensures that a fresh database is created and migrated before every test executed in that class.

Laravel makes it easy to employ a testing strategy that creates database records on the fly using Model Factories:

Using this approach, your database/factories/ModelFactory.php file should grow to contain a definition for every model that exists in your application.

It’s an overhead that pays back in dividends!

Your tests returning green will always let you know that your migration files are free from bugs, and that you’re easily able to generate dummy data for you application.

The final step is to actually seed the database. At this stage, it should be very easy to use Laravel’s in-built helpers to generate Seeder classes where you can use the familiar factory method to insert dummy records into the database. You can craft the seed data in any way you like – what I’ve found that works best is to try to include as much “real looking” data as possible.

Here’s an example of how I seed the super administrator users into the database:

Wrapping Up

With a few lines of code you can display a list of users on the login page (not to be shown on production!) to make it easy for product owners to grab an e-mail and login with a dummy account:

Screen Shot 2016-11-19 at 16.25.18

Let me know if you have any other tips for crafting your staging environment in the comments!

Refactoring Advanced Eloquent Filters To Collections

Amo Chohan wrote a very good article detailing a technique he uses to clean up controllers when dealing with complex search queries in eloquent.

I’m also enjoying Adam Wathan‘s latest release: Refactoring to Collections – a read guaranteed to make you smarter.

Amo really nailed the functionality here – but I think the final class presented could use some of Adam’s magic to make it just a little bit better. Let’s be honest – I’ve just been looking for an excuse to try out some of Adam’s techniques…

Below is the original class, and then my refactors.

Removing Static

Since all methods in this class are static, we can’t keep track of state. We end up passing around the variables that we’re using (the Request and Builder in this instance) to every method.

By adding a private constructor, we can keep the Api of the class the same, but internally gain the benefits of working with an object!

I’ve refactored the apply method to create a new instance of the object, and then call the appropriate methods to return the desired results. Since we don’t need the actual Request object anywhere else, I’ve gone ahead and created a collection out of the inputs for future use.

Introducing a Null Object

Currently we’re looping through the request inputs, and checking to see if we can find an existing filter to apply:

One way to get rid of that conditional is by introducing a null object that effectively accepts the query, but does nothing with it.

The above method allows us to refactor the applyDecoratorsFromRequest method (that I’ve renamed to applyFilters) into the following:

Since our filters are now a collection, we have access to the each method which I’ve used here instead. The getFilterFor method will always return a valid class that we can use – even if it is just a null object – allowing us to forego any conditionals!

I’m returning  $this just for convenience’s sake to allow me to chain my method calls.


A refactor to my own method getFiltersFor could also more heavily make use of collections, and we can end up with a solution that completely eliminates loops and conditionals:

We’ve reworked the flow to do the following:

  • Map all filter names to class names
  • Filter out class names that aren’t implemented
  • Map all class names into new instances
  • Get the appropriate filter object, or return a new NullFilter if it doesn’t exist

In this case it’s debatable as to whether this second refactor adds any value – but an interesting solution nonetheless.

Moving On

For those who suffer from long and complicated index methods on your controllers, I urge you to read the original article by Amo.

As a side note, all of the refactors that I performed on the class (creating a private instance, introducing a null object, and refactoring to collections) were all lessons learned from Adam Wathan’s Refactoring to Collections book.

Happy coding!

Stress Testing a Website with Throng

I recently needed to stress test a website to ensure that it could hold up in the real world – after some searching I stumbled upon Throng – a simple app for Mac. It allowed me to hit my website with concurrent requests for a specified period of time.

You can download the 7-day trial of Throng from this link.

Screen Shot 2016-05-09 at 5.22.35 PM

The app allows you to specify a URL you’d like to hit, a time limit in seconds, and the number of concurrent users to simulate. Hit Start and it will immediately begin hitting your website – charting the average response time.


Load Impact – An online tool service to stress test your website. I tried it until my credits ran out – but I found that for my (simple) needs Throng was a better choice.

Creating an Embeddable Javascript Widget

One of the updates I’m working on for WhichBeach is the ability for other website owners to embed WhichBeach widgets that will display up-to-date beach data. This is very much a work in progress, but I’d like to share.

I’ve never done anything like this before, so I thought I’d start by taking some inspiration from Facebook’s Like Button implementation:

To break it down, Facebook’s script injects a new script tag that pulls in their Javascript SDK. They’re also ensuring that the script is only injected once into the page.

I think I can make this work for me too:

Great. Now all that’s left is to write a Javascript SDK! I’ll need to expose that on /js/sdk.js and add all my widget logic in there.

In due time… if anyone has any tips and resources that they think I should be using – let me know in the comments!

Applying Text Transform to Form Inputs

I often find myself in the situation where a design calls for form inputs to transform the user’s text. It’s pretty easy to do nowadays:

This is what it looks like:

But – I’ve always found these types of interactions frustrating whenever I come across them. The expectation of the user is jarred when the user’s input changes unexpectedly. I decided to do some research and found a couple of posts on the subject.

Is text-transform uppercase frustrating when used in input form fields?

Here’s a discussion on UX Stack Exchange that suggests transforming the text after the field loses focus. This javascript solution does seem slightly better than a simple CSS transform – but I still find it awkward when I come across these forms.

The User Experience (UX) Of CSS Text-Transform On Form Input Fields

Ben Nadal wrote an interesting commentary about how CSS transforms on form inputs causes frustration and confusion. I agree with him here.

So what’s the best way to do it?

I say – don’t ever transform a user’s input in a form field. User’s have come to expect forms to act in a certain way, and changing that (even for the better) gives your form an extra learning curve.

If you really need to transform the user’s input somehow, I did come up with an elegant solution recently – by showing the user a summary of their form input (after or while they’re filling in the form) you can get the best of both worlds.

The user can refer to the form where the text that they have input remains unchanged. At the same time, they can see the summary where they text that they’ve input has been modified in some way.

I’d be interested to hear if anyone has any thoughts or findings on the topic in the comments!

Immutable Objects Will Improve Your Life

Learning about immutable objects improved my PHP code thoroughly. I’ve listed some helpful resources below that really helped me grasp the concept of immutability and value objects.

As a quick example, if your code sometimes looks like this:

When it should be looking (more) like this:

Then I urge you to read up on immutable objects. Below are some of the articles that I found most helpful.

The Fowler Money Pattern

Here’s a very well written article, using Money as an example of an object that should be immutable.


Difference Between Entities and Value Objects

Philip Brown wrote a very good explanation highlighting the differences between Entities (which are what your regular Laravel models are) and Value Objects. A real eye opener.


An Interesting Discussion

Here’s a discussion debating the pros and cons of immutable objects, and a little history.


Immutability in Javascript

I’m been doing a lot of development in Vue.js recently, though I’ve never worked towards immutability in javascript. The article linked is an interesting read, and led me to discover immutability.js – a library created by Facebook with a number of immutable data structures.


I wonder – does anyone have any experience in working with immutability in javascript with Vue.js or other similar frameworks? I’d be interested to hear your thoughts on the subject in the comments.

Logging Guzzle Requests

I’m working on a project that involves consuming a Json REST Api – it’s sometimes useful to log the requests being made – both for debugging and historical purposes.

I’m using the popular Guzzle package to consume the Api, which has the middleware concept built in – allowing developers to register hooks during the request lifecycle, and in our case – log them.

According to the Guzzle documentation, the way to do this is to pass a new HandlerStack with our logging middleware into our Client instance.

The syntax for creating a new Guzzle instance is as follows:

The $handlerStack will eventually hold the middleware that handles the logging.

Setting up the log file

Before I can set up the middleware, I need to instantiate something that handles writing our log messages to file. I’ll use the Monolog package to handle this – it makes it easy to achieve my desired criteria of having a daily log file next to my default laravel.log.

In my AppServiceProvider I’ll set up a helper function to create the logger:

Setting up the middleware

Guzzle’s logging middleware requires a logger (that I’ve just created above) and a MessageFormatter instance that controls what gets logged.

I’ll set up a helper function to create the middleware:

The $messageFormat is a string that “Formats log messages using variable substitutions for requests, responses, and other transactional data.” Possible substitutions can be seen here – but I’ve come up with some handy ones:

Logging the request:  {method} {uri} HTTP/{version} {req_body}
Logging the response:  RESPONSE: {code} - {res_body}

Creating the HandlerStack

Now that I have a way to easily new up an instance of Guzzle’s logging middleware, I can create a new HandlerStack to push the middleware onto:

Logging the request and response separately

I decided to log the request and response in two separate log entries. It seems like the only way to accomplish this is to push multiple logging middlewares to Guzzle, so I set up a helper function to create a HandlerStack with all the required logging middleware from an array of message format strings that I would like to log.

And there we have it! Now, adding multiple loggers to our Guzzle Client is as easy as the code below:

A short note on working with Guzzle responses

After setting up the logger, I realised that I was no longer able to access the response body – it turns out it was my mistake. 

Previously, I was accessing the response content using the following line:

But it turns out that this gets the “remaining contents of the body as a string” – and since the middleware already accessed the body in order to log it, there isn’t any content remaining to retrieve.

The correct way to access the response content is to cast the body to a string:


Pushing Logic to Custom Collections

This is a technique that I recently found useful. Eloquent models allow you to specify a custom collection object to be returned – which sometimes can be a great place to put some business logic.

While refactoring WhichBeach, I used a custom collection to move some logic from the Beach model to a custom BeachCollection. This allowed me to test the logic in isolation.

Creating the Custom Collection

I created a new class extending Laravel’s Eloquent Collection:

In my model, I instructed Laravel to use my custom collection:

Adding the Logic

Now that I had a place to put my custom code, I could add any number of helper methods to be used throughout my application:

Edit: The above code block has been improved after an excellent suggestion by Joseph Silber in the comments.

This has given me the ability to write more fluent code when dealing with beaches:

Being able to write the line above is a big plus for me – the less cognitive load required to understand the intended output, the better.

Let me know of any good examples of using custom collections in the comments!