Connecting third-party PHP libraries to Joomla

PHP libraries are convenient because they can be accessed from anywhere in the Application: from a plugin, component model, module, etc. If someone has already solved a similar problem and designed it as a library (and even updates it), it makes sense to connect this library to your Joomla. For example, to develop a payment method for an online store, you need the official library of a payment aggregator. Or you are satisfied with the official PHP SDK of some CRM.

Composer

Joomla does not support working with Composer directly. In order to use the library in your work, you need to “wrap” it in a Joomla extension like library and install. Accepted in serious projects versioning approach all components of the project: the code has been checked more than once, tested and approved for use in production.

You create a package with your library and install it wherever you need it. As new versions of the library are released, you update your wrapper and get all the benefits of working with Joomla extensions: updating extensions in a standard way, including through the CLI. View Changelog extensions in the admin panel BEFORE updating, etc.

View the Changelog extension in the admin panel BEFORE upgrading to Joomla 5.

View Changelog extensions in the admin panel BEFORE updating to Joomla 5.

Joomla, PCR, Symfony

Joomla complies with PCR standards, so in this regard it is convenient to work with. Joomla core includes some Symfony packages (console, string, var-dumper, yaml, error-handler and others), so if you suddenly want to add more, they will fit like a glove and work well. See what else costs in Joomla besides components Symfony possible in libraries/vendor.

How to wrap a PHP library in a Joomla extension?

Nothing complicated. Library files are usually located in the src folder. Next to this folder you need to create an XML manifest of the Joomla extension according to the documentation (manual.joomla.org). Then we pack everything into a zip archive and you're done! Can be installed.

If the library requires its own tables in the database for its operation, during installation or update you need to add the necessary files with SQL queries. Since Joomla 4+ works with namespacesit is important to specify this for the extension namespace in the XML manifest. I will give a shortened example of an XML manifest for the Joomla library.

<?xml version="1.0" encoding="UTF-8" ?>
<extension type="library" method="upgrade">
     <name>WebTolk AmoCRM library</name>
     <libraryname>Webtolk/Amocrm</libraryname>
     <version>1.2.1</version>
     ...
     <namespace path="src">Webtolk\Amocrm</namespace>
     <files>
          <folder>src</folder>
          <filename>amocrm.xml</filename>
     </files>
</extension>

Tag <libraryname> means that the folder src from our archive will be copied to JPATH_SITE/libraries/Webtolk/Amocrm. In section <files> we indicate What from the archive you need to put it there. A <namespace path="src">Webtolk\Amocrm</namespace> says it's for a folder src V JPATH_SITE/libraries/Webtolk/Amocrm must be registered namespace Webtolk\Amocrm.

Important points!

  • Before Joomla 4.2.7, essentially the tag from the XML manifest did not work. Therefore, it was necessary to add a system plugin to the library kit that would register the namespace on an event (Event Dispatcher) onAfterInitialise with the help JLoader. Accordingly, it was necessary to assemble the package from the library and the plugin. Starting with Joomla 4.2.7 it has been fixed and you can do without the plugin.

  • For now, updating the library = reinstalling. That is, the extension is removed and installed. This decision was made somewhere in the bowels of Joomla 3.x versions. Why? – hidden under the PR mountains. We need to look. Why is this important? Because when installing any extension, an entry is created in the “registry” of extensions – in the database in the table #__extensions. This table has 2 columns like TEXTparams And custom_data. And this, you see, is a considerable amount of data. If you store some library parameters in the database using Joomla\CMS\Helper\LibraryHelperthen you need to take into account this behavior of the installer and, when updating the library, first save and then add back the saved parameters to the installer script of the extension.

<?php
use Joomla\CMS\Helper\LibraryHelper;
use Joomla\CMS\Cache\Cache;

/**
 * Function called before extension installation/update/removal procedure commences.
 *
 * @param   string            $type     The type of change (install or discover_install, update, uninstall)
 * @param   InstallerAdapter  $adapter  The adapter calling this method
 *
 * @return  boolean  True on success
 *
 * @since   1.0.0
 */
public function preflight(string $type, InstallerAdapter $adapter): bool
{
    if ($type == 'uninstall')
    {
        return true;
    }

    /**
     *
     *  Joomla при обновлении расширений типа library по факту удаляет их (вместе с данными в базе),
     *  а потом устанавливает заново.
     *  Дабы избежать потерь данных библиотеки из базы пишем этот костыль.
     *
     * @see https://github.com/joomla/joomla-cms/issues/39360
     *
     */

    if ($type == 'update')
    {
        $lib_params = LibraryHelper::getParams('Webtolk/Amocrm');
        $jconfig    = $this->app->getConfig();
        $options    = array(
            'defaultgroup' => 'wt_amo_crm_temp',
            'caching'      => true,
            'cachebase'    => $jconfig->get('cache_path'),
            'storage'      => $jconfig->get('cache_handler'),
        );
        $cache      = Cache::getInstance('', $options);
        $cache->store($lib_params, 'wt_amo_crm_temp');

    }

    return true;

}

And in the method postflight() Accordingly, we put the saved parameters back using LibraryHelper::saveParams('Webtolk/Amocrm', $lib_params);.

  • For the library to work, it must be enabled in the extension manager (Menu – System – Management – Extensions).

  • Often, for the library to work, certain parameters are needed (API keys, tokens, etc.), which must be specified by people in the Joomla admin panel. For these purposes, it is convenient to write a plugin (the library extension does not have its own interface for setting parameters). Either the system one or your custom group – it doesn’t matter. Inside your library, you can get plugin parameters quite quickly like this:

<?php
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;

if (PluginHelper::isEnabled('system', 'wt_amocrm'))
   {
      $plugin        = PluginHelper::getPlugin('system', 'wt_amocrm');
      $params        = \json_decode($plugin->params);
      $param = $params->param;
      // ИЛИ можно использовать Joomla\Registry\Registry
      $params = new Registry($plugin->params);
      $param = $params->get('param', 'defatul value if empty');
   }

In conclusion, I want to share the opinion of a member of the Joomla community, developer – @kernUSR, which he expressed in Joomla chat:

In Joomla, as in the Airborne Forces – “There are no impossible tasks.”

Useful Resources

Community Resources:

Telegram:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *