用于 PHP 的 Facebook SDK v4 最小示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23413854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Facebook SDK v4 for PHP Minimal Example
提问by Nick Weisser
I'm trying to get the minimal example
我试图得到最小的例子
using Facebook\FacebookSession;
FacebookSession::setDefaultApplication('YOUR_APP_ID','YOUR_APP_SECRET');
// Use one of the helper classes to get a FacebookSession object.
// FacebookRedirectLoginHelper
// FacebookCanvasLoginHelper
// FacebookJavaScriptLoginHelper
// or create a FacebookSession with a valid access token:
$session = new FacebookSession('access-token-here');
// Get the GraphUser object for the current user:
try {
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo $me->getName();
} catch (FacebookRequestException $e) {
// The Graph API returned an error
} catch (\Exception $e) {
// Some other error occurred
}
from the READMEworking, but I don't understand what the first line of code means. Where do I have to put the PHP file using that minimal code example within the SDK file structure. I tried directly in the src folder, but that returns the following PHP error
从README工作,但我不明白第一行代码是什么意思。我必须使用 SDK 文件结构中的最小代码示例将 PHP 文件放在哪里。我直接在 src 文件夹中尝试,但返回以下 PHP 错误
[01-May-2014 20:12:26 Europe/Berlin] PHP Parse error: syntax error, unexpected 'Facebook' (T_STRING) in /Applications/MAMP/htdocs/facebook-php-sdk-v4/src/test.php on line 9
The file structure looks like this
文件结构看起来像这样
├── src
│?? ├── Facebook
│?? │?? ├── FacebookAuthorizationException.php
│?? │?? ├── FacebookCanvasLoginHelper.php
│?? │?? ├── FacebookClientException.php
│?? │?? ├── FacebookJavaScriptLoginHelper.php
│?? │?? ├── FacebookOtherException.php
│?? │?? ├── FacebookPermissionException.php
│?? │?? ├── FacebookRedirectLoginHelper.php
│?? │?? ├── FacebookRequest.php
│?? │?? ├── FacebookRequestException.php
│?? │?? ├── FacebookResponse.php
│?? │?? ├── FacebookSDKException.php
│?? │?? ├── FacebookServerException.php
│?? │?? ├── FacebookSession.php
│?? │?? ├── FacebookThrottleException.php
│?? │?? ├── GraphLocation.php
│?? │?? ├── GraphObject.php
│?? │?? ├── GraphSessionInfo.php
│?? │?? ├── GraphUser.php
│?? │?? └── fb_ca_chain_bundle.crt
│?? └── test.php
回答by zoomi
have recently solved this. as there is autoload.php file available with sdk you dont need to use require etc etc. just include that autoload.php on the start
最近解决了这个问题。因为 sdk 有 autoload.php 文件,所以你不需要使用 require 等。只需在开始时包含 autoload.php
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// start session
// init app with app id and secret
FacebookSession::setDefaultApplication( 'app-id','app-secret' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://yourhost/facebook/' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
} else {
// show login url
echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';
}
?>
after this you must have to check the path in autoload.php file
在此之后,您必须检查 autoload.php 文件中的路径
$base_dir = defined('FACEBOOK_SDK_V4_SRC_DIR') ? FACEBOOK_SDK_V4_SRC_DIR : __DIR__ . '/src/Facebook/';
this line is default code if u have changed the name of directories like placed all the files from /src/Facebook/ to /sdk/ then just replace the name
always check the included path by using die(__DIR__ . '/src/Facebook/');
to make sure if it is correct.
如果您已更改目录名称(例如将所有文件从 /src/Facebook/ 放置到 /sdk/),则此行是默认代码,然后只需替换名称,请始终使用检查包含的路径die(__DIR__ . '/src/Facebook/');
以确保它是否正确。
回答by Ahmet
There is a complete (working) example here: http://metah.ch/blog/2014/05/facebook-sdk-4-0-0-for-php-a-working-sample-to-get-started/
这里有一个完整的(工作)示例:http: //metah.ch/blog/2014/05/facebook-sdk-4-0-0-for-php-a-working-sample-to-get-started/
Code:
代码:
session_start();
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('APPID','SECRET');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://www.metah.ch/' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo print_r( $graphObject, 1 );
} else {
// show login url
echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';
}
回答by mamdouh alramadan
I think you need to change this line:
我认为你需要改变这一行:
using Facebook\FacebookSession;
to
到
use Facebook\FacebookSession;
to use a namespace in php the keyword is use
more on php using namespaces
要use
在php 中使用命名空间,关键字更多是在php using namespaces 上
Update:
更新:
using namespaces does not automatically include the script, you either need to include the path in your autoload (if you have one) or simply:
using namespaces 不会自动包含脚本,您要么需要在自动加载中包含路径(如果有),要么只是:
include 'path/to/FacebookSession.php';
Update2:first, please read the php namespaces in the manual, second, no, if it is already included in the original class then you don't. or if it is adhering to psr-* then you can use some autoloader or use spl_autoload_register
Update2:首先,请阅读手册中的php命名空间,其次,不,如果它已经包含在原始类中,那么您就没有。或者如果它坚持 psr-* 那么你可以使用一些自动加载器或使用spl_autoload_register
回答by Denis V
To avoid using require
or require_once
and to have a better project structure you should follow the following steps:
为了避免使用require
orrequire_once
并拥有更好的项目结构,您应该遵循以下步骤:
- Install composer from https://getcomposer.org/
Create
composer.json
file in your web application root with the following contents:{ "require" : { "facebook/php-sdk-v4" : "4.0.*" } }
Call
php composer.phar install
- Create a folder
src/Acme/App
- Create a file
src/Acme/App/Run.php
with the following contents:
- 从https://getcomposer.org/安装 composer
composer.json
使用以下内容在您的 Web 应用程序根目录中创建文件:{ "require" : { "facebook/php-sdk-v4" : "4.0.*" } }
称呼
php composer.phar install
- 创建文件夹
src/Acme/App
- 创建一个
src/Acme/App/Run.php
包含以下内容的文件:
<?php
<?php
namespace Acme\App;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
class Run {
const APP_ID = 'app_id';
const APP_SECRET = 'app_secret';
public function __construct()
{
FacebookSession::setDefaultApplication(self::APP_ID, self::APP_SECRET);
// ...your code goes here...
}
}
- Create an
index.php
file with the following contents:
- 创建一个
index.php
包含以下内容的文件:
<?php
<?php
$loader = require_once 'vendor/autoload.php';
$loader->add('Acme\App', __DIR__.'/src');
$app = new Run();
This will be a skeleton of your Facebook application (all your further classes should follow PSR-4 standard). Using composer's autoloader you will not need to use require_once
for classes in any registered namespace.
这将是您的 Facebook 应用程序的骨架(您所有进一步的类都应遵循 PSR-4 标准)。使用作曲家的自动加载器,您将不需要require_once
在任何注册的命名空间中使用类。
P.S. You may want to remove all your libraries from the web root. It will help to prevent direct access from web to them. Then you can just adjust the pathnames and keep only index.php in your web root. I hope, it's clear.
PS 您可能希望从 Web 根目录中删除所有库。这将有助于防止从网络直接访问他们。然后你可以调整路径名并在你的 web 根目录中只保留 index.php。我希望,很清楚。
回答by rm-vanda
Yeah, the new tutorials aren't very helpful.
是的,新教程不是很有帮助。
I'm running through them, myself, and just to get the examples to work, I did:
我自己正在运行它们,只是为了让示例起作用,我做了:
function facebookLoader($class) {
require "/path/to/facebook-php-sdk-v4-master/src/" . str_replace("\", "/", $class) . ".php";
}
spl_autoload_register("facebookLoader");
Facebook\FacebookSession::setDefaultApplication([...]
and prepended Facebook\
anywhere where was a class name being called.
并Facebook\
在任何调用类名的地方添加。
Also, there's a part in the tutorial where it says to use:
FacebookRedirectLoginHelper();
此外,教程中有一部分说要使用:
FacebookRedirectLoginHelper();
When you, in fact, still have to give the thing input:
实际上,当您仍然必须给事物输入时:
FacebookRedirectLoginHelper("http://yourRedirectUri.com/");
FacebookRedirectLoginHelper("http://yourRedirectUri.com/");
Got me through the tutorial - ! Now on to figuring out how to get the user's email/complete profile information.
让我完成了教程 - !现在开始弄清楚如何获取用户的电子邮件/完整的个人资料信息。
回答by rajesh ujade
- PHP Version 5.4.0 or higher is required.
- Facebook uses Implementations of PSR-4. Hence You dont have to use require or require_once or include or include_once.
- In PSR-4, you just need packagename(namespace) i.e. directory name and class file name only.It will register classes dynamically from given package name.Ex.:-
use packaname\classname
. - You will find the file autoload.phpin Facebook SDK Autoloadroot directory.
use
is used to load dynamic classes usingspl_autoload_register
- Facebook register all library using
autoload.php
orautoload_fb.php
- You have to find autoload.php in your downloaded library like
facebook-php-sdk-v4-4.0-dev/
. - If you just wants to use Facebooklibrary from download source.Then you have to copy autoload.phpin your root directory or in Facebook directory.
- defined constant for
FACEBOOK_SDK_V4_SRC_DIR
i.e. path of the facebook library - You need to do as below to usein php
- 需要 PHP 5.4.0 或更高版本。
- Facebook 使用PSR-4 的实现。因此,您不必使用require 或 require_once 或 include 或 include_once。
- 在 PSR-4 中,你只需要 packagename(namespace) 即目录名和类文件名。它会从给定的包名动态注册类
use packaname\classname
。例如:- 。 - 您将在Facebook SDK Autoload根目录中找到autoload.php文件。
use
用于加载动态类使用spl_autoload_register
- Facebook 使用
autoload.php
或注册所有图书馆autoload_fb.php
- 您必须在下载的库中找到 autoload.php,例如
facebook-php-sdk-v4-4.0-dev/
. - 如果您只是想从下载源使用Facebook库。那么您必须将autoload.php复制到您的根目录或 Facebook 目录中。
- 为
FACEBOOK_SDK_V4_SRC_DIR
ie facebook 库的路径定义常量 - 您需要执行以下操作才能在 php 中使用
Note:I have copied /var/www/stack/24006673/facebook-php-sdk-v4-4.0-dev/src/Facebook
directory and /var/www/stack/24006673/facebook-php-sdk-v4-4.0-dev/autoload.php
file in root directory /var/www/stack/24006673/
注意:我已经复制了根目录下的/var/www/stack/24006673/facebook-php-sdk-v4-4.0-dev/src/Facebook
目录和/var/www/stack/24006673/facebook-php-sdk-v4-4.0-dev/autoload.php
文件/var/www/stack/24006673/
define('FACEBOOK_SDK_V4_SRC_DIR','/var/www/stack/24006673/Facebook/');
require_once("autoload.php");
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
FacebookSession::setDefaultApplication('YOUR_APP_ID','YOUR_APP_SECRET');
回答by Arvind Bhardwaj
I solved it. Just use following line at the top of your script:
我解决了。只需在脚本顶部使用以下行:
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/facebook-php-sdk-v4/src/Facebook/');
and you are done.
你就完成了。
回答by Fischer Tirado
just put this on include page:
只需将其放在包含页面上:
require DIR. '/path/to/facebook-php-sdk-v4/autoload.php';
需要DIR。'/path/to/facebook-php-sdk-v4/autoload.php';
Also call the class before use, each time you need:
每次需要时,请在使用前调用该类:
use Facebook\FacebookSession;
使用 Facebook\FacebookSession;