Facebook PHP SDK Zend Framework 2

In ZF1 I would generally include 3rd party API wrappers (Facebook, MailChimp, Google, etc) in Bootstrap.php using something like:

1
2
3
4
5
6
7
8
9
protected function _initIncludes(){
include_once( 'MobileDetect/Mobile-Detect-2.php' );
include_once( 'Facebook/php-sdk-v3.1.1-27/src/facebook.php' );
include_once( 'Google/google-api-php-client-0.5.0/src/apiClient.php' );
include_once( 'MailChimp/MCAPI-1.3.class.php' );
} //_initIncludes

Facebook PHP SDK Zend Framework 2

However there isn’t really anywhere appropriate to ‘include’ things this way in ZF2. Ideally we want to include the 3rd party class in the (/all) module(s) that actually use it, but without trying to include it more than once.

The best way I’ve found of doing this is to add the 3rd party class into Zend’s Class Map Autoloader like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function getAutoloaderConfig() {
return array(
'ZendLoaderClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
array(
'Facebook' => 'vendor/facebook/php-sdk/src/facebook.php',
),
),
'ZendLoaderStandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}

This shows how I’m including the ‘Facebook’ class. Remember that ZF2 chdir()’s to the application’s root directory, so the path is relative to that. I can then just create a Facebook instance with:

1
2
3
4
5
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));

Adding things via this method has a few advantages:

  1. The class is included lazily.
  2. The same entry can be included in multiple modules without there being a risk of conflict.
  3. Zend’s Class Map Autoloader is very, very, very fast.

Comments are closed.