The Grumpy Programmer's Guide To Building Testable PHP Applications by Chris Hartjes

The Grumpy Programmer's Guide To Building Testable PHP Applications by Chris Hartjes

Author:Chris Hartjes [Chris Hartjes]
Language: eng
Format: epub, mobi
Publisher: leanpub.com
Published: 2012-01-12T05:00:00+00:00


If it’s not yours, wrap it up.

If you are using a 3rd-party API to do something like user authentication you will quickly discover that it becomes very difficult to test. A typical scenario might be where this 3rd-party API requires a redirect to their site where the user fills out some information and then they are returned to your application with some sort of token that says you are who you claim to be. Now this is good for you because it removes the burden of managing those credentials yourself, but bad because how do you test such a thing?

You might be lucky and the application you are using has a way to capture the request and response cycle. The sample application for this guide does not, so let’s think of how you could use something like Facebook Connect.

The answer is, of course, that you place your use of a 3rd party authentication service inside a wrapper. Stay with me as I explain the logic.

Instead of thinking “how do I create a test where I talk to Facebook” you turn it on it’s head and say “how do I create a test for an authentication service that uses Facebook Connect as it’s data source?”. I hope you can see the difference.

The normal way of using Facebook Connect is that you use their own SDK (or if you are a masochist you write your own OAuth implementation) which basically redirects the user to Facebook, where they enter their login credentials for the site. If their credentials are good, they are redirected back to your application along with a token that you then can use to get information about the user.

In cases where I myself have used Facebook Connect for authentication purposes I tend to store information about the user in the session and then refer to it later. Here’s an example of what I mean:

1 <?php 2 // Assume $facebookUser is the object representing info about our user 3 4 $_SESSION['email'] = $facebookUser->getEmail(); 5 $_SESSION['name'] = 6 $facebookUser->getFirstName() . 7 ' ' . 8 $facebookUser->getLastName(); 9 10 // In other parts of the app when I need to check if the user is 11 // authenticated properly 12 13 if (isset($_SESSION['email'])) { 14 // Execute the desired functionality 15 } else { 16 // Redirect user to log in with Facebook Connect 17 }



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.