Articles


Drupal 7: How to include php library in Drupal 7?

Drupal 7: How to include php library in Drupal 7?



Posted byUttam Kotekar,30th Jul 2016

It is very easy to registers js and css libraries using the hook_library(), However if you want to register php libraries you should consider the Library API module. Library API module is very useful module which introduces a common repository for libraries in sites/all/libraries. So lets begin including php library in your custom module. Here in this article we will try to include "stripe-php-master" library as an example.

Intially download the "stripe-php-master" module and place it in sites/all/libraries folder. Make sure you have enabled Library API module. After uploading the stripe library folder we need to initialize it using the hook_library_info(). Please see the below code, code goes to your module file (example.module).

/**
 * Implements hook_libraries_info().
 */
function example_libraries_info() {
  return array(
    'stripe-php-master' => array(
      'name' => 'Stripe API Client Library for PHP for refunds',
      'vendor url' => 'https://stripe.com/',
      'download url' => 'https://github.com/stripe/stripe-php',
      'version' => '3.4.0',
      'dependencies' => array(),
      'files' => array(
        'php' => array(
          'init.php',
        ),
      ),
    ),
  );
}

Once you intialize it you need to the load the library whenever it is necessary, so lets create a custom function and load the library in it and make use of this function to include stripe library whenever stripe functionality is required.

/**
 * Brings the more upto date Stripe PHP client library into scope
 */
function example_stripe_load_library() {
  $library = libraries_load('stripe-php-master');
  if (!$library || empty($library['loaded'])) {
    watchdog('mp_returns', 'Failure to load Stripe API PHP Client Library.', array(), WATCHDOG_CRITICAL);
    return FALSE;
  }
  else {
    return TRUE;
  }
}

Thats it. You can simple call the example_stripe_load_library() function to include the library whenever you need stripe functionality to take place something like this.

$status = example_stripe_load_library();
if ($status) {
  \Stripe\Stripe::setApiKey(variable_get('stripe_private', ''));
  // your stripe functionality goes here
}

NOTE: Make you have specified proper folder name "stripe-php-master" in the hook_library_info().

Categories