Using PHP to Implement a Fluent Interface to Any REST API


May 12, 2016
Written by
Elmer Thomas
Contributor
Opinions expressed by Twilio contributors are their own

Using PHP to Implement a Fluent Interface to Any REST API

PHP HTTP client library updatesAs we upgrade our open source SendGrid API libraries to support our v3 Web API, we've also been updating our API client libraries to contain as few dependencies as possible. Part of this effort entails creating brand new, lean HTTP clients to drive communication with our APIs. The last HTTP client I wrote about was Python, and in this post, we'll explore our new PHP HTTP client that will drive our new v5 SendGrid PHP library, using a working prototype.

The remainder of this post will reference the following code:

Fluent Interfaces

A fluent interface allows us to create API calls dynamically, without having to pre-define every endpoint. For example, we can use `$client->path()->to()->the()->endpoint()->get()` for a call to: `GET /path/to/the/endpoint` without defining methods for `path`, `to`, `the` and `endpoint`.

Method Chaining

Generally, we simply return `$this` when chaining our method calls together. However, in this case we are returning a new version of the `Fluent` object, because we want to preserve fragments of the URL for later reuse see line 11.

Reflection

To capture the method calls dynamically, we need to use PHP’s magic `__call` PHP docs method, which is called whenever the object can't find the method you are calling see line 20.

Handling Special Cases

To handle special cases or to allow users to specify a complete path as a string, we use the `_()` method see line 9. You pass in a string and receive a new object with the name of your string added to the URL path variable.

References & Acknowledgements

Matt Bernier

After I completed the Python implementation of a fluent interface, the next day, Matt came up with a working prototype of the PHP version. Yes, he’s got PHP skillz to pay the billz. You can check out Matt's post about the developer experience at SendGrid, Using DX to Solve Your Next Email Apocalypse.

Websites

The following references helped me understand the concepts described in this post: Thank you for dropping by, and if you decide to build something with this library or have some contributions, please open an issue in our GitHub repo.

What’s next? Stay tuned as we continue to release similar blog posts for each the other languages we support, like Ruby, C#, Node.js, Go and Java. To start testing your email and integration, sign up for a free SendGrid account today.

Recommended For You



Most Popular


Send With Confidence

Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.