Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Rob Allen:
Writing PSR-7 middleware
Nov 05, 2015 @ 19:48:58

In this new post to his site Rob Allen talks about PSR-7 compatible middle ware and shows examples of writing it to work with frameworks that support the PSR-7 structure. His examples revolve around Slim 3 but could be used in other supporting frameworks just as easily.

Within Slim 3's Request object, there's a method called getIp() which is determines the client's IP address. However it's rather simplistic and potentially risky as it checks the X-Forwarded-For header with no ability to ignore this header or whitelist whether we trust the final proxy in the chain. Determining the client's IP address is an ideal use-case for middleware as we can inspect the headers in the request and then set an attribute so that middleware further down the chain can use it.

With this goal in mind, he shows how to create the middleware that uses the __invoke method to execute the required logic and call the next middleware in the chain. In his example he makes use of a pseudo-method determineClientIpAddress that does the work of detecting the IP address and then sets the value as a part of the request object (as an attribute). He also shows how to configure the middleware to select an attribute name and how to attach the middleware to a few different framework types.

tagged: pst7 middleware slim3 framework ipaddress tutorial

Link: http://akrabat.com/writing-psr-7-middleware/


Trending Topics: