Matthew Daly's Blog

I'm a web developer in Norfolk. This is my blog...

19th February 2017 3:50 pm

My First Laravel Package

For some time now I’ve had a Laravel middleware I use extensively to add ETags to HTTP requests. I often use it for work projects, but obviously copying and pasting it all the time was a pain. I always meant to create a package for it, but I didn’t want to do so until such time as I had some proper tests for it. Now I’ve finally figured out how to test middleware in isolation and I’ve got around to adding tests and creating a proper package for it.

It’s available on Github and Packagist if you want to use it.

18th February 2017 9:25 pm

Integrating Behat With Laravel

The Gherkin format used by tools like Cucumber is a really great way of specifying how your application will work. It’s easy for even non-technical stakeholders to understand, it makes it natural to break your tests into easily reusable steps, and it encourages you to think about the application from an end-user’s perspective. It’s also one of the easiest ways to get started writing automated tests when you first start out - it’s much more intuitive to a junior developer than lower-level unit tests, and is easier to add to a legacy project that may not have been built with testability in mind - if you can drive a browser, you can test it.

Behat is a PHP equivalent. Combined with Mink, it allows for easy automated acceptance tests of a PHP application. However, out of the box it doesn’t integrate well with Laravel. There is Jeffrey Way’s Behat Laravel extension, but it doesn’t seem to be actively maintained and seems to be overkill for this purpose. I wanted something that I could use to run integration tests using PHPUnit’s assertions and Laravel’s testing utilities, and crucially, I wanted to do so as quickly as possible. That meant running a web server and using an automated web browser wasn’t an option. Also, I often work on REST API’s, and browser testing isn’t appropriate for those - in API tests I’m more interested in setting up the fixtures, making a single request, and verifying that it does what it’s meant to do, as quickly as possible.

As it turns out, integrating Behat and Laravel isn’t that hard. When using Behat, your FeatureContext.php file must implement the Behat\Behat\Context\Context interface, but as this interface does not implement any methods, you can extend any existing class and declare that it implements that interface. That means we can just extend the existing Tests\TestCase class in Laravel 5.4 and gain access to all the same testing utilities we have in our regular Laravel tests.

Then, in the constructor we can set environment variables using putenv() so that we can set it up to use an in-memory SQLite database for faster tests. We also use the @BeforeScenario hook to migrate the database before each scenario, and the @AfterScenario hook to roll it back afterwards.

Here’s the finished example:

<?php
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Tests\TestCase;
use Behat\Behat\Tester\Exception\PendingException;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\User;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Illuminate\Contracts\Console\Kernel;
/**
* Defines application features from the specific context.
*/
class FeatureContext extends TestCase implements Context
{
use DatabaseMigrations;
protected $content;
/**
* Initializes context.
*
* Every scenario gets its own context instance.
* You can also pass arbitrary arguments to the
* context constructor through behat.yml.
*/
public function __construct()
{
putenv('DB_CONNECTION=sqlite');
putenv('DB_DATABASE=:memory:');
parent::setUp();
}
/** @BeforeScenario */
public function before(BeforeScenarioScope $scope)
{
$this->artisan('migrate');
$this->app[Kernel::class]->setArtisan(null);
}
/** @AfterScenario */
public function after(AfterScenarioScope $scope)
{
$this->artisan('migrate:rollback');
}
/**
* @Given I visit the path :path
*/
public function iVisitThePath($path)
{
$response = $this->get('/');
$this->assertEquals(200, $response->getStatusCode());
$this->content = $response->getContent();
}
/**
* @Then I should see the text :text
*/
public function iShouldSeeTheText($text)
{
$this->assertContains($text, $this->content);
}
/**
* @Given a user called :user exists
*/
public function aUserCalledExists($user)
{
$user = factory(App\User::class)->create([
'name' => $user,
]);
}
/**
* @Given I am logged in as :user
*/
public function iAmLoggedInAs($user)
{
$user = User::where('name', $user)->first();
$this->be($user);
}
}

Note that I’ve added a few basic example methods for our tests. As you can see, we can call the same methods we normally use in Laravel tests to make assertions and HTTP requests. If you’re using Dusk, you can also call that in the same way you usually would.

We might then write the following feature file to demonstrate our application at work:

Feature: Login
Background:
Given a user called "Alan" exists
And a user called "Bob" exists
And a user called "Clare" exists
And a user called "Derek" exists
And a user called "Eric" exists
Scenario: Log in as Alan
Given I am logged in as "Alan"
And I visit the path "/"
Then I should see the text "Laravel"
Scenario: Log in as Bob
Given I am logged in as "Bob"
And I visit the path "/"
Then I should see the text "Laravel"
Scenario: Log in as Clare
Given I am logged in as "Clare"
And I visit the path "/"
Then I should see the text "Laravel"
Scenario: Log in as Derek
Given I am logged in as "Derek"
And I visit the path "/"
Then I should see the text "Laravel"
Scenario: Log in as Eric
Given I am logged in as "Eric"
And I visit the path "/"
Then I should see the text "Laravel"

We can then run these tests with vendor/bin/behat:

$ vendor/bin/behat
Feature: Login
Background: # features/auth.feature:3
Given a user called "Alan" exists # FeatureContext::aUserCalledExists()
And a user called "Bob" exists # FeatureContext::aUserCalledExists()
And a user called "Clare" exists # FeatureContext::aUserCalledExists()
And a user called "Derek" exists # FeatureContext::aUserCalledExists()
And a user called "Eric" exists # FeatureContext::aUserCalledExists()
Scenario: Log in as Alan # features/auth.feature:10
Given I am logged in as "Alan" # FeatureContext::iAmLoggedInAs()
And I visit the path "/" # FeatureContext::iVisitThePath()
Then I should see the text "Laravel" # FeatureContext::iShouldSeeTheText()
Scenario: Log in as Bob # features/auth.feature:15
Given I am logged in as "Bob" # FeatureContext::iAmLoggedInAs()
And I visit the path "/" # FeatureContext::iVisitThePath()
Then I should see the text "Laravel" # FeatureContext::iShouldSeeTheText()
Scenario: Log in as Clare # features/auth.feature:20
Given I am logged in as "Clare" # FeatureContext::iAmLoggedInAs()
And I visit the path "/" # FeatureContext::iVisitThePath()
Then I should see the text "Laravel" # FeatureContext::iShouldSeeTheText()
Scenario: Log in as Derek # features/auth.feature:25
Given I am logged in as "Derek" # FeatureContext::iAmLoggedInAs()
And I visit the path "/" # FeatureContext::iVisitThePath()
Then I should see the text "Laravel" # FeatureContext::iShouldSeeTheText()
Scenario: Log in as Eric # features/auth.feature:30
Given I am logged in as "Eric" # FeatureContext::iAmLoggedInAs()
And I visit the path "/" # FeatureContext::iVisitThePath()
Then I should see the text "Laravel" # FeatureContext::iShouldSeeTheText()
5 scenarios (5 passed)
40 steps (40 passed)
0m0.50s (19.87Mb)

Higher level tests can get very tedious if you’re not careful - you wind up setting up the same fixtures and making the same requests many times over. By using Behat in this way, not only are you writing your tests in a way that is easy to understand, but you’re also breaking it down into logical, repeatable steps, and by passing arguments in each step you limit the amount of repetition. It’s also fast if you aren’t running browser-based tests, making it particularly well-suited to API testing.

29th November 2016 11:00 pm

Testing Laravel Middleware

It’s widely accepted that high-level integration tests alone do not make for a good test suite. Ideally each individual component of your application should have unit tests, which test that component in isolation. These unit tests are usually much quicker to run, making it easier to practice test-driven development. However, it can sometimes be hard to grasp how to test that one component on its own.

The other day I had an issue with several middleware classes for a Laravel application and I wanted to verify that they were working as expected. Sounds like a job for dedicated unit tests, but I hadn’t tested custom middleware in isolation before, and figuring out how to do so took a while.

Laravel middleware accepts an instance of Illuminate\Http\Request, itself based on the Symfony request object, as well as a closure for the action to take next. Depending on what the middleware does, it may return a redirect or simply amend the existing request or response. So in theory you can instantiate a request object, pass it to the middleware, and check the response. For middleware that does something simple, such as redirecting users based on certain conditions, this is fairly straightforward.

In this example we have a fairly useless piece of middleware that checks to see what the route is for a request and redirects it if it matches a certain pattern:

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectFromAdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->is('admin*')) {
return redirect('/');
}
return $next($request);
}
}

While this example is of limited use, it wouldn’t take much work to develop it to redirect conditionally based on an account type, and it’s simple enough to demonstrate the principles involved. In these tests, we create instances of Illuminate\Http\Request and pass them to the middleware’s handle() method, along with an empty closure representing the response. If the middleware does not amend the request, we get the empty response from the closure. If it does amend the request, we get a redirect response.

<?php
use Illuminate\Http\Request;
class RedirectFromAdminMiddlewareTest extends TestCase
{
public function testRedirectMiddlewareCalledOnAdmin()
{
// Create request
$request = Request::create('http://example.com/admin', 'GET');
// Pass it to the middleware
$middleware = new App\Http\Middleware\RedirectFromAdminMiddleware();
$response = $middleware->handle($request, function () {});
$this->assertEquals($response->getStatusCode(), 302);
}
public function testRedirectMiddlewareNotCalledOnNonAdmin()
{
// Create request
$request = Request::create('http://example.com/pages', 'GET');
// Pass it to the middleware
$middleware = new App\Http\Middleware\RedirectFromAdminMiddleware();
$response = $middleware->handle($request, function () {});
$this->assertEquals($response, null);
}
}

For middleware that fetches the response and acts on it, things are a little more complex. For instance, this is the Etag middleware I use on many projects:

<?php
namespace App\Http\Middleware;
use Closure;
class ETagMiddleware {
/**
* Implement Etag support
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Get response
$response = $next($request);
// If this was a GET request...
if ($request->isMethod('get')) {
// Generate Etag
$etag = md5($response->getContent());
$requestEtag = str_replace('"', '', $request->getETags());
// Check to see if Etag has changed
if($requestEtag && $requestEtag[0] == $etag) {
$response->setNotModified();
}
// Set Etag
$response->setEtag($etag);
}
// Send response
return $response;
}
}

This acts on the response object, so we need to pass that through as well. Fortunately, Mockery allows us to create a mock of our response object and set it up to handle only those methods we anticipate being called:

<?php
use Illuminate\Http\Request;
class ETagMiddlewareTest extends TestCase
{
/**
* Test new request not cached
*
* @return void
*/
public function testModified()
{
// Create mock response
$response = Mockery::mock('Illuminate\Http\Response')->shouldReceive('getContent')->once()->andReturn('blah')->getMock();
$response->shouldReceive('setEtag')->with(md5('blah'));
// Create request
$request = Request::create('http://example.com/admin', 'GET');
// Pass it to the middleware
$middleware = new App\Http\Middleware\ETagMiddleware();
$middlewareResponse = $middleware->handle($request, function () use ($response) {
return $response;
});
}
/**
* Test repeated request not modified
*
* @return void
*/
public function testNotModified()
{
// Create mock response
$response = Mockery::mock('Illuminate\Http\Response')->shouldReceive('getContent')->once()->andReturn('blah')->getMock();
$response->shouldReceive('setEtag')->with(md5('blah'));
$response->shouldReceive('setNotModified');
// Create request
$request = Request::create('http://example.com/admin', 'GET', [], [], [], [
'ETag' => md5('blah')
]);
// Pass it to the middleware
$middleware = new App\Http\Middleware\ETagMiddleware();
$middlewareResponse = $middleware->handle($request, function () use ($response) {
return $response;
});
}
public function teardown()
{
Mockery::close();
}
}

In the first example we mock out the getContent() and setEtag() methods of our response to make sure they get called, and then pass the request to the middleware, along with a closure that returns the response. In the second example, we also mock out setNotModified() to ensure that the correct status code of 304 is set, and add an ETag to our request. In this way we can easily test our middleware in isolation, rather than having to resort to building up our entire application just to test one small method.

Middleware is a convenient place to put functionality that’s needed for many routes, but you shouldn’t neglect testing it, and ideally you shouldn’t have to resort to writing a slow integration test to test it works as expected. By mocking out your dependencies, it’s generally not too hard to test it in isolation, resulting in faster and more robust test suites.

26th November 2016 9:40 pm

Easy Static Asset Versioning in PHP

It’s prudent to cache static assets such as images, Javascript and CSS to improve performance, but that raises the issue of changes not being reflected in your site due to visitor’s browsers retaining the cached versions. Many content management systems and frameworks already handle this for you (such as Laravel’s Elixir build system), but what if you have to work with a legacy application that doesn’t do this?

Fortunately there’s a quite easy solution in PHP. Using the filemtime() function described here, we can get a Unix timestamp for when a file was last altered. This is perfect to use to identify when a file last changed, because by appending a new query string to the file name when loading it, we can trick the browser into thinking it’s a new file when it’s not, as in this example for a CodeIgniter application:

<link rel="stylesheet" type="text/css" href="<?=$path?>?v=<?=filemtime($path)?>">

Obviously, this is a bit repetitive, so you may want to refactor this into some kind of template helper to make it easier to use, but the underlying principle applies to most programming languages. For instance, if you wanted to do so in a Handlebars template, you might want to create a helper something like this:

var fs = require('fs');
var Handlebars = require('handlebars');
Handlebars.registerHelper('version', function (path) {
return path + '?v=' + fs.statSync(path).mtime.getTime();
});

Where more robust solutions such as Elixir are already available, I’d advise making full use of them. However, this technique is a quick and easy way to implement versioning for static assets in existing projects.

13th November 2016 4:15 pm

Building a Phonegap App With Laravel and Angular - Part 4

In this instalment we’ll return to the back end. What we’ve done so far is typical of the kind of proof of concept we might do for a client early on, before going back and implementing the full set of features later on. Now we’ll go back and start to improve on that rather quick-and-dirty API by making sure we follow a few best practices.

For those of you who want to follow the Laravel Phonegap tutorials, I’ve created a dedicated category here for those tutorials. This category include RSS and Atom feeds, so if you only want to read those posts, you can do so. I’ve also done the same for the Django tutorials.

The Repository pattern

One of the issues we currently have with our API is that we’re passing our Eloquent models into our controllers. This may not seem like a huge issue, but it means that our controllers are tightly coupled to the Eloquent ORM, so if we wanted to switch to another ORM, or to a completely different database such as MongoDB, we’d have to amend our controllers. That’s not good.

However, using the Repository pattern we can first of all define an interface for our repository, and then create a repository class that implements that interface. That way we can interact with the repository class in our controllers, rather than using Eloquent models directly. Then, if we want to switch databases, we merely amend the repository class to change the implementation of those methods, without having to touch our controllers. Also, it makes it much easier to test our controllers in isolation, because we can easily mock our repository class using Mockery and hard-code the response, so our tests won’t touch the database and will therefore run more quickly. We won’t touch on that this time, but it’s a very significant advantage.

If you haven’t used interfaces before in PHP, they aren’t that hard. They merely specify what methods an object implementing that method must have and what arguments they must accept, but do not specify the details of the implementation. This makes it easy to determine if a class implements an interface correctly, because it will throw an exception if it doesn’t.

<?php
namespace AnimalFriend\Repositories\Interfaces;
interface PetRepositoryInterface {
public function all();
public function findOrFail($id);
public function create($input);
}

That’s all there is to it. We define it using the interface keyword and we specify the methods it must implement. Save this file at app/Repositories/Interfaces/PetRepositoryInterface.php.

Next, we implement the repository class:

<?php
namespace AnimalFriend\Repositories;
use AnimalFriend\Pet;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface;
class EloquentPetRepository implements PetRepositoryInterface {
private $pet;
public function __construct(Pet $pet)
{
$this->pet = $pet;
}
public function all()
{
return $this->pet->all();
}
public function findOrFail($id)
{
return $this->pet->findOrFail($id);
}
public function create($input)
{
return $this->pet->create($input);
}
}

Save this to app/Repositories/EloquentPetRepository.php. Note how the methods closely mirror the underlying Eloquent methods, but they don’t need to - you could change the underlying implementation of each method, but the repository would still work in exactly the same way.

To make this work, we need to make a few changes elsewhere. In composer.json, we need to add the new Repositories folder to our classmap:

"autoload": {
"classmap": [
"database",
"app/Repositories"
],
"psr-4": {
"AnimalFriend\\": "app/"
}
},

And in app/Providers/AppServiceProvider.php, we need to bind our new files:

<?php
namespace AnimalFriend\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\PetRepositoryInterface',
'AnimalFriend\Repositories\EloquentPetRepository'
);
}
}

With that done, we can now update app/Http/Controllers/PetController.php to use the repository:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface as Pet;
class PetController extends Controller
{
private $pet;
public function __construct(Pet $pet) {
$this->pet = $pet;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Get all pets
$pets = $this->pet->all();
// Send response
return response()->json($pets, 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Get pet
$pet = $this->pet->findOrFail($id);
// Send response
return response()->json($pet, 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Our repository is now injected automatically into the controller. To make this work we need to run the following command:

$ composer dump-autoload

Running our tests should confirm that everything is still working:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 897 ms, Memory: 18.00MB
OK (12 tests, 46 assertions)

Let’s do the same for the User model. First we implement our interface in app/Repositories/Interfaces/UserRepositoryInterface.php:

<?php
namespace AnimalFriend\Repositories\Interfaces;
interface UserRepositoryInterface {
public function all();
public function findOrFail($id);
public function create($input);
}

Next we create our repository at app/Repositories/EloquentUserRepository.php:

<?php
namespace AnimalFriend\Repositories;
use AnimalFriend\User;
use AnimalFriend\Repositories\Interfaces\UserRepositoryInterface;
use JWTAuth;
use Hash;
class EloquentUserRepository implements UserRepositoryInterface {
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function all()
{
return $this->user->all();
}
public function findOrFail($id)
{
return $this->user->findOrFail($id);
}
public function create($input)
{
$user = new $this->user;
$user->email = $input['email'];
$user->name = $input['name'];
$user->password = Hash::make($input['password']);
$user->save();
// Create token
return JWTAuth::fromUser($user);
}
}

Note how we’ve moved much of the logic for creating a user into the create() method, and we return the token, not the user model. This makes sense as right now we only ever want to get a token back when we create a user. Later that may change, but there’s nothing stopping us adding a new method to implement that behaviour alongside this.

Then we update app/Http/Controllers/UserController.php to use our repository:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\UserRepositoryInterface as User;
use JWTAuth;
use Hash;
class UserController extends Controller
{
private $user;
public function __construct(User $user) {
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate request
$valid = $this->validate($request, [
'email' => 'required|email|unique:users,email',
'name' => 'required|string',
'password' => 'required|confirmed'
]);
// Create token
$token = $this->user->create($request->only(
'email',
'name',
'password'
));
// Send response
return response()->json(['token' => $token], 201);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

And add a new binding in app/Providers/AppServiceProvider.php:

<?php
namespace AnimalFriend\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\PetRepositoryInterface',
'AnimalFriend\Repositories\EloquentPetRepository'
);
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\UserRepositoryInterface',
'AnimalFriend\Repositories\EloquentUserRepository'
);
}
}

Note that we bind the two sets separately - this allows Laravel to figure out which one maps to which.

Let’s run our tests to make sure nothing is broken:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 956 ms, Memory: 18.00MB
OK (12 tests, 46 assertions)

Now that we’ve got our repositories in place, we’re no longer tightly coupled to Eloquent, and have a more flexible implementation which is easier to test.

Separating our models from our JSON with Fractal

Another problem with our API is that our representation of our data is tightly coupled to our underlying implementation of our models. We therefore can’t change our models without potentially changing the data returned by the API. We need to separate our representation of our data from our actual model so that we can more easily specify the exact data we want to return, regardless of the underlying database structure.

Enter Fractal. From the website:

Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc.

In other words, Fractal lets you specify the format your data will take in one place so that it’s easier to return that data in a desired format. We’ll use Fractal to specify how we want our API responses to be formatted.

Install Fractal with the following command:

$ composer require league/fractal

Then amend the classmap in composer.json:

"autoload": {
"classmap": [
"database",
"app/Repositories",
"app/Transformers"
],
"psr-4": {
"AnimalFriend\\": "app/"
}
},

Then create the folder app/Transformers and run composer dump-autoload. We’re now ready to write our first transformer. Save this as app/Transformers/PetTransformer.php:

<?php
namespace AnimalFriend\Transformers;
use AnimalFriend\Pet;
use League\Fractal;
class PetTransformer extends Fractal\TransformerAbstract
{
public function transform(Pet $pet)
{
return [
'id' => (int) $pet->id,
'name' => (string) $pet->name,
'type' => (string) $pet->type,
'available' => (bool) $pet->available,
'picture' => (string) $pet->picture
];
}
}

The transform method specifies how we want to represent our objects with our API. We can return only those attributes we want to expose, and amend the structure as we see fit. We could easily represemt relations in whatever manner we see fit, whereas before we needed to amend our queries to return the data in the right format, which would potentially be cumbersome.

Now let’s amend PetController.php to use this:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface as Pet;
use AnimalFriend\Transformers\PetTransformer;
use League\Fractal;
use League\Fractal\Manager;
class PetController extends Controller
{
private $pet, $fractal;
public function __construct(Pet $pet, Manager $fractal) {
$this->pet = $pet;
$this->fractal = $fractal;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Get all pets
$pets = $this->pet->all();
// Format it
$resource = new Fractal\Resource\Collection($pets, new PetTransformer);
$data = $this->fractal->createData($resource)->toArray();
// Send response
return response()->json($data, 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Get pet
$pet = $this->pet->findOrFail($id);
// Format it
$resource = new Fractal\Resource\Item($pet, new PetTransformer);
$data = $this->fractal->createData($resource)->toArray();
// Send response
return response()->json($data, 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Note that by default, Fractal places our data inside a dedicated data namespace. This is good because it leaves a place for us to put metadata such as pagination links, but it does mean our controller test has been broken. Let’s fix it:

<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
class PetControllerTest extends TestCase
{
use DatabaseMigrations;
/**
* Test fetching pets when unauthorised
*
* @return void
*/
public function testFetchingPetsWhenUnauthorised()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create request
$response = $this->call('GET', '/api/pets');
$this->assertResponseStatus(400);
}
/**
* Test fetching pets when authorised
*
* @return void
*/
public function testFetchingPets()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets', [], $headers)
->seeJsonStructure([
'data' => [
'*' => [
'id',
'name',
'type',
'available',
'picture'
]
]
]);
$this->assertResponseStatus(200);
}
/**
* Test fetching pet when unauthorised
*
* @return void
*/
public function testFetchingPetWhenUnauthorised()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Send request
$response = $this->call('GET', '/api/pets/'.$pet->id);
$this->assertResponseStatus(400);
}
/**
* Test fetching pet which does not exist
*
* @return void
*/
public function testFetchingPetDoesNotExist()
{
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets/1', [], $headers);
$this->assertResponseStatus(404);
}
/**
* Test fetching pet when authorised
*
* @return void
*/
public function testFetchingPet()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets/'.$pet->id, [], $headers)
->seeJsonStructure([
'data' => [
'id',
'name',
'type',
'available',
'picture'
]
]);
$this->assertResponseStatus(200);
}
}

We’re also going to amend our test settings to use the array backend for the cache, as this does not require any external dependencies, but still allows us to tag our cache keys (I’ll cover that in a future instalment). Change the cache settings in phpunit.xml as follows:

<env name="CACHE_DRIVER" value="array"/>

Let’s run our tests to make sure everything’s fine:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 859 ms, Memory: 18.00MB
OK (12 tests, 44 assertions)

At present our User controller doesn’t actually return anything, and the auth only ever returns the token, so it’s not worth while adding a transformer now.

Wrapping up

That ends this lesson. We haven’t added any functionality, but we have improved the design of our API, and we’re now ready to develop it further. As usual, the backend repository has been tagged as lesson-4.

Next time we’ll start adding the additional functionality we need to our API.

Recent Posts

Run Your Tests Locally With Sismo

Profiling Your Laravel Application With Clockwork

Snapshot Test Your Vue Components With Jest

Enforcing a Coding Standard With PHP Codesniffer

Decorating Laravel Repositories

About me

I'm a web and mobile app developer based in Norfolk. My skillset includes Python, PHP and Javascript, and I have extensive experience working with CodeIgniter, Laravel, Django, Phonegap and Angular.js.