-
Notifications
You must be signed in to change notification settings - Fork 24
Handling A Response
This library acts as a go between for your program and MailChimp's API, it acts in order to make understanding and using MailChimps API more simple. One way it does this is by providing ways to interface with the responses you get from MailChimps API. When MailChimp response to a request this library parses that response and populate an instance of a MailchimpResponse
object. This class allows you to act on a requests response by giving you a set of getters
and setters
for each part of the response Recieved from MailChimp. let say we made a get request against the root endpoint of the MailChimp API like this:
$mailchimp->account()->get();
The MailChimp API documentation states that we should see a response similar to this:
HTTP/1.1 200 OK
Server: nginx
Content-Type: application/json; charset=utf-8
Content-Length: 2340
Vary: Accept-Encoding
X-Request-Id: bca135bf-860c-4614-a07b-a70b062680c0
Link: <https://api.mailchimp.com/schema/3.0/Root.json>; rel="describedBy"
Date: Tue, 15 Sep 2015 15:13:50 GMT
Connection: keep-alive
{
"account_id": "8d3a3db4d97663a9074efcc16",
"account_name": "Freddie's Jokes",
"email": "[email protected]",
"role": "owner",
"contact": {
"company": "Freddie's Jokes",
"addr1": "675 Ponce De Leon Ave NE",
"addr2": "Suite 5000",
"city": "Atlanta",
"state": "GA",
"zip": "30308",
"country": "US"
},
"last_login": "2015-09-15 14:25:37",
"total_subscribers": 413,
"_links": [...]
}
However this library will recive this response and break it down into a much more digestible instance of a MailchimpResponse
. So what can we do with our response? Here are a list of methods we can use to derive information from our response object:
$response->getHeaders() // returns a map of the headers received with the response
$response->getHttpCode() // returns the HTTP code sent with the response
$response->getBody() // returns the response body as a string
$response->wasSuccessful() // returns true if the http code is in the 200 range
$response->wasFailure() // returns true if the http code was outside of the 200 range
If we want to be able to reach into the response body and act on its contents in PHP however we will need to deserialize its contents. This can be achieved by calling the following on our response from our earlier request:
$account = $response->deserialize();
We can now reach into our response using PHP object notation. So if I wanted the account id for this account I can now call:
$id = $account->account_id;
Alternatively the deserialize()
method takes an argument to deserialize your MailChimp response to arrays. This is done by calling deserialize(true)
. Should you choose this option you would then reach into your response like this:
$id = $account[account_id];