using composer packages in a wordpress plugin

I’m developing a wordpress plugin, and the plugin makes use of a composer package. For reference the plugin I’m developing is here:

https://github.com/tunapanda/wp-h5p-xapi

Read More

I’m at the stage where it works locally, and I would like to publish it to the wordpress plugin repository.

In order to use the plugin, I need to run composer install inside the plugin directory to have the composer package installed. My question is, how does this plays together with the plugin repository and what the best practice to get this to work? Because obviously, if I would just publish the plugin to the repository and if someone would install it from there it would not work, since then the composer package which is a dependency would not be installed.

I see two different ways to deal with this:

  • Put my vendor directory under source control and check it in to the repository. This doesn’t feel like an ideal solution since I would lose much of the point of using a package manager such as composer in the first place.

  • Avoid using composer all together, and instead just take the code for the package I need and put that under source control.

So my question is, what is the best practice for this? Anyone who could point me to a reference wordpress plugin that uses external dependencies?

Related posts

2 comments

  1. Your plugin looks very interesting, and it’s cool to see a supplement for the H5P project being made already.

    As for you question, I’m not sure there is a best practice or optimal way to do this. From what I can see, the most common thing to do is to include the 3rd party library in the plugin, or require a plugin that already has it. One issue would of course be if it’s the version you need.

    If you decide to do it, I would recommend including it after the plugins are loaded, and that you do some checks before you include it, e.g.

    function load_my_library() {
      if ( !class_exists( 'MyLibraryClass' ) ) {
        require_once( plugin_dir_path(__FILE__) . 'my-library/class.php' );
      }
    }
    add_action( 'plugins_loaded', 'load_my_library', 0 );
    

    I hope this answer is of some use to you. Good luck with you plugin!

  2. Use spl_autoload_register function. It will allow to autoload the file on declaring the class.

    function custom_autoloader($class) {
      include 'lib/' . $class . '.php';
    }
     
    spl_autoload_register('custom_autoloader');
     
    $objFooBar = new FooBar();
    

Comments are closed.