15

My plugin requires vendor library dependencies and api keys set. What is the recommended way to register an external library? I would also like to configure the public api keys separately for stage and production environments — is there a way to set these in craft/config with the rest of the multi-environment configuration? Or is it better to create a plugin config file of some kind?

Currently I am having to include these in each of my service methods (and something similar again in my javascript files):

private function _saveStripeCustomer($account, $token = NULL)
{
    require_once(CRAFT_PLUGINS_PATH . 'businesslogic/vendor/stripe/lib/Stripe.php');
    \Stripe::setApiKey("sk_test_xxxxxxxxxxxxxxxxxx");

    // ...
}

I'm not familiar with composer. I don't know if that can perhaps help here.

Douglas McDonald
  • 13,457
  • 24
  • 57

1 Answers1

26

Composer!

There's already a package for Stripe: https://packagist.org/packages/stripe/stripe-php

  1. Install composer.

  2. Add a composer.json file in your plugin's root folder.

  3. Add this to the composer.json file:

    { "require": { "stripe/stripe-php": "1.17.2" } }

  4. Run php composer.phar update from your plugin's root folder.

  5. The library will be installed in a /vendor folder in your plugin.

  6. Add an init() method to your main plugin's class file with this in it:

    require CRAFT_PLUGINS_PATH.'/pluginhandle/vendor/autoload.php';

And you're done.

Composer will handle autoloading all of the class files, so you don't need to worry about it.

If you ever want to update the Stripe library to a newer release, grab the version number from the packagist site, update your composer.json file with it and run php composer.phar update again.

Michael Rog
  • 3,420
  • 1
  • 18
  • 27
Brad Bell
  • 67,440
  • 6
  • 73
  • 143