9

What is the preferred way of loading a third party library in a plugin? I'm trying to develop a plugin to extend SproutForms so that users get signed up to Campaign Monitor.

So far I've got an interface in the CP where users can provide their API keys and List ID's into the database, so now I just need to actually add the CM API library.

I know I can just require it, but I was wondering if there is a better way of doing this? Also where would I store the library, just in pluginname/lib/?

13

I second Brad on this, if there is a composer package, use that.

Whether you use a composer package or a library not found on packagist.org you'll still need to load it so that your plugin can make use of it.

Generally speaking, there are plenty of places where you can import/require third party libraries from but my recommendation would be to do so from the init() method in your main plugin class. As far as where to put it, I would go with one of these 5 acceptable directory names used most often in no particular order library, common, third, lib, or src. I'll use library in the following example.

Once you've downloaded/installed your third party library, your directory structure might look something like this...

plugin
    PluginClass.php
    controllers
    templates
    ...
    library
        campaignmonitor
    OR
    library
        vendor
            composer
            campaignmonitor
            ...

Given the outlined directory structure above, your init() method might look something like this...

// PluginClass.php
public function init()
{
    require_once './library/campaignmonitor/SomeClass.php';
    require_once './library/campaignmonitor/SomeOtherClass.php';
    ...
    // If using composer
    require_once './library/vendor/autoload.php';
}

I'd also like to point out that Craft::import() can theoretically import using glob as in Craft::import('plugins.pluginname.library.*) which is cool because those don't get required right away but lazy loaded when needed. However, this only works for class in the Craft namespace so you'll have to stick to a method described above: )

Hope that helps!

| improve this answer | |
  • 1
    Your answer is way better than mine. – Brad Bell Nov 23 '14 at 2:45
  • You are too kind Brad! Truth is, I wish I could spend a little more time tackling some questions. – Selvin Ortiz Nov 23 '14 at 3:48
  • Is there an updated answer for this for Craft 3? – kmgdev Sep 20 '18 at 23:26
3

Ideally the third party library would be available as a composer package (you can check on http://packagist.org) and you'd install it via composer. By default that will put it in a vendor folder in your plugin.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.