开发者

Best way for using Facebook PHP SDK in PHP website for authentication Specially in Zend

I am worki开发者_Go百科ng on a website that will work with Facebook. I saw several ways that people can connect to Facebook. I somehow got confused. As I understood, I can use Facebook for authentication in these ways:

  1. Using "fb:login-button" and after Facebook did its job, redirect or refresh my page and make a new instance from facebook.php in order to get current User and the rest.
  2. Using the SDK only and make a new instance from it and generate LoginUrl and LogOutUrl and after user Logged in, continue as the way that we did in the first one.

ps1: Are the ways that I wrote here, are all the ways I can use Facebook's SDK? ps2: I confused as much as that I cannot code! I cannot decide is the way I'm going, will support all the things I want in the future!!!


Facebook authentication uses OAuth. Both the options you listed use this mechanism, the only difference is that option one uses Facebook's Javascript SDK, and the 2nd uses Facebook's PHP one. I would say your choice comes down to whether you would prefer to interact with Facebook using PHP or JS.

As for how to integrate, if you go with the PHP SDK I would suggest creating a controller plugin in which you call the getUser() method on the SDK. The SDK will return the user data if the user is logged in and null otherwise. You can then assign this user object to the view if it's set, along with the logout URL. If not, you can assign the login URL and add a login link somewhere appropriate in your app.

Something along the lines of:

class Your_Plugin_Login extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $facebook = Zend_Registry::get('facebook');
        $user = $facebook->getUser();

        if ($user) {
            // assign the user object to the view for easy access later
            $layout = Zend_Layout::getMvcInstance();
            $view = $layout->getView();

            $view->user = $user;
            $view->logoutUrl = $facebook->getLogoutUrl();

        } else {
            $view->loginUrl = $facebook->getLoginUrl();
            $view->user = false;
        }
    }

}

(This code assumes the Facebook SDK is stored in the registry as 'facebook', and that you are using Zend_Layout.)

For added bonus points you could store the user data in Zend_Auth, which would be particularly handy if you are using Zend_Auth already on your site for standard logins.

For an alternative route, Chris Weber wrote a decent (if not quite finished) OAuth2/Zend_Service_Facebook implementation which you can find here: https://github.com/chrisweb/oauth-2---facebook---zend-framework-components/blob/master/README but I eventually dropped this and wrote a ZF-friendly wrapper around the standard SDK instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜