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`.
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
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
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.
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
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