Difference between revisions of "Using own library in your extensions"

From Joomla! Documentation

(Several spelling, punctuation, URL and grammar corrections.)
(Several markup changes.)
 
Line 2: Line 2:
 
{{version/tutor|2.5,3.1}}
 
{{version/tutor|2.5,3.1}}
 
<translate><!--T:1-->
 
<translate><!--T:1-->
There are several approaches to registering your own library with Joomla's autoloader and then use it in your extension. All these approaches are based on the <code>JLoader</code> class. For this tutorial, assume that your library is located in the ''/libraries/mylib'' folder.</translate>
+
There are several approaches to registering your own library with Joomla's autoloader and then use it in your extension. All these approaches are based on the ''JLoader'' class. For this tutorial, assume that your library is located in the ''/libraries/mylib'' folder.</translate>
  
 
<translate>
 
<translate>
Line 8: Line 8:
 
</translate>
 
</translate>
 
<translate><!--T:3-->
 
<translate><!--T:3-->
Classes in a folder that follow a naming convention can be registered collectively with JLoader's [https://api.joomla.org/cms-2.5/classes/JLoader.html#method_discover discover()] method. The discover method looks at the file names in a folder and registers classes based on those names. Additional arguments can be used to update the class register and recurse into sub-folders.</translate>
+
Classes in a folder that follow a naming convention can be registered collectively with JLoader's [https://api.joomla.org/cms-2.5/classes/JLoader.html#method_discover ''discover()''] method. The ''discover'' method looks at the file names in a folder and registers classes based on those names. Additional arguments can be used to update the class register and recurse into sub-folders.</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
 
// Register all files in the /libraries/mylib folder as classes with a name like: MyLib<Filename>
 
// Register all files in the /libraries/mylib folder as classes with a name like: MyLib<Filename>
 
JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');
 
JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:4-->
 
<translate><!--T:4-->
As you can see this method working by following the special naming convention:
+
This method works by following the special naming convention:
* <code>/mylib/user.php</code> will be equal to <code>MylibUser</code>
+
* ''/mylib/user.php'' will be equal to ''MylibUser''
* <code>/mylib/userhelper.php</code> will be equal to <code>MylibUserHelper</code></translate>
+
* ''/mylib/userhelper.php'' will be equal to ''MylibUserHelper''</translate>
  
 
<translate>
 
<translate>
Line 23: Line 23:
 
</translate>
 
</translate>
 
<translate><!--T:6-->
 
<translate><!--T:6-->
Since Joomla Platform 12.1 (Joomla! CMS 3+), there is the ability to register where the auto-loader will look based on a class prefix (previously only the "J" prefix was supported, bound to the ''/libraries/joomla'' folder). This is done with the [https://api.joomla.org/cms-3/classes/JLoader.html#method_registerPrefix registerPrefix()] method and allows for several scenarios:</translate>
+
Since Joomla Platform 12.1 (Joomla! CMS 3+), there is the ability to register where the autoloader will look based on a class prefix. (Previously only the ''J'' prefix was supported, bound to the ''/libraries/joomla'' folder.). This is done with the [https://api.joomla.org/cms-3/classes/JLoader.html#method_registerPrefix registerPrefix()] method and allows for several scenarios:</translate>
  
 
<translate><!--T:7-->
 
<translate><!--T:7-->
* A developer can register the prefix of custom classes and a root path to allow the auto-loader to find them.</translate>
+
* A developer can register the prefix of custom classes and a root path to allow the autoloader to find them.</translate>
 
<translate><!--T:8-->
 
<translate><!--T:8-->
* A developer can register an extra path for an existing prefix. (For example, this allows the Joomla CMS to have custom libraries but still using the "J" prefix.)</translate>
+
* A developer can register an extra path for an existing prefix. (For example, this allows the Joomla CMS to have custom libraries but still using the ''J'' prefix.)</translate>
 
<translate><!--T:9-->
 
<translate><!--T:9-->
* A developer can register a force override for a prefix. This could be used to completely override the core classes with a custom replacement.</translate>
+
* A developer can register a forced override for a prefix. This could be used to completely override the core classes with a custom replacement.</translate>
  
 
<translate>
 
<translate>
Line 36: Line 36:
 
</translate>
 
</translate>
 
<translate><!--T:11-->
 
<translate><!--T:11-->
The class name must be in CamelCase and each segment of the name will represent a folder path where the last segment of the name is the name of the class file. If there is only one part to the class name, the auto-loader will look for the file in a folder of the same name. Folder names must be in lower case.</translate>
+
The class name must be in CamelCase and each segment of the name will represent a folder path where the last segment of the name is the name of the class file. If there is only one part to the class name, the autoloader will look for the file in a folder of the same name. Folder names must be in lower case.</translate>
  
 
<translate><!--T:12-->
 
<translate><!--T:12-->
'''Examples:'''
+
'''Examples'''
* <code>PrefixUserModel</code> class should be located in <code>PATH_TO_PREFIX/user/model.php</code>
+
* ''PrefixUserModel'' class should be located in ''PATH_TO_PREFIX/user/model.php''
* <code>PrefixUser</code> class should be located in <code>PATH_TO_PREFIX/user/user.php</code></translate>
+
* ''PrefixUser'' class should be located in ''PATH_TO_PREFIX/user/user.php''</translate>
  
 
<translate><!--T:13-->
 
<translate><!--T:13-->
 
'''Our scenario examples:'''
 
'''Our scenario examples:'''
* <code>MylibUserHelper</code> class should be located in <code>/libraries/mylib/user/helper.php</code>
+
* ''MylibUserHelper'' class should be located in ''/libraries/mylib/user/helper.php''
* <code>MylibUser</code> class should be located in <code>/libraries/mylib/user/user.php</code></translate>
+
* ''MylibUser'' class should be located in ''/libraries/mylib/user/user.php''</translate>
  
 
<translate><!--T:14-->
 
<translate><!--T:14-->
There is no limit to the depth to which the auto-loader will search, providing it forms a valid path based on the CamelCase natural of the class name. Note that while acronyms and names such as HTML, XML and MySQL have a standard presentation in text, such terms should observe CamelCase rules programmatically. ("HTML" becomes "Html", "XML" becomes "Xml" and so on.)</translate>
+
There is no limit to the depth to which the autoloader will search, providing it forms a valid path based on the CamelCase natural of the class name. Note that while acronyms and names such as HTML, XML and MySQL have a standard presentation in text, such terms should observe CamelCase rules programmatically. ("HTML" becomes "Html", "XML" becomes "Xml" and so on.)</translate>
  
 
<translate>
 
<translate>
 
=== Usage === <!--T:15-->
 
=== Usage === <!--T:15-->
 
</translate>
 
</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
// Tell the auto-loader to look for classes starting with '"Mylib" in a specific folder.
+
// Tell the autoloader to look for classes starting with "Mylib" in a specific folder.
JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');</source>
+
JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');</syntaxhighlight>
<source lang="php">
+
<syntaxhighlight lang="php">
// Tell the auto-loader to also look in the "/libraries/cms" folder for "J" prefixed classes.
+
// Tell the autoloader to also look in the "/libraries/cms" folder for "J" prefixed classes.
JLoader::registerPrefix('J', JPATH_PLATFORM . '/cms');</source>
+
JLoader::registerPrefix('J', JPATH_PLATFORM . '/cms');</syntaxhighlight>
<source lang="php">
+
<syntaxhighlight lang="php">
// Tell the auto-loader to reset the "J" prefix and point it to a custom fork of the platform.
+
// Tell the autoloader to reset the "J" prefix and point it to a custom fork of the platform.
JLoader::registerPrefix('J', '/my/platform/fork', true);</source>
+
JLoader::registerPrefix('J', '/my/platform/fork', true);</syntaxhighlight>
  
 
<translate>
 
<translate>
=== Note on registerPrefix === <!--T:16-->
+
=== Note on ''registerPrefix'' === <!--T:16-->
 
</translate>
 
</translate>
 
<translate><!--T:17-->
 
<translate><!--T:17-->
 
For Joomla CMS 2.5, the prefix cannot start with the same letter. The system will try to load the first matched. For example, if we register prefix ''JM'', as ''J'' prefix exists, the JLoader will find ''J'' prefix. When it searches for the class in the registered path of ''J'', no class will be found.</translate>
 
For Joomla CMS 2.5, the prefix cannot start with the same letter. The system will try to load the first matched. For example, if we register prefix ''JM'', as ''J'' prefix exists, the JLoader will find ''J'' prefix. When it searches for the class in the registered path of ''J'', no class will be found.</translate>
 
+
 
 
<translate>
 
<translate>
 
== Namespace Loader == <!--T:18-->
 
== Namespace Loader == <!--T:18-->
Line 78: Line 78:
 
<translate><!--T:20-->
 
<translate><!--T:20-->
 
'''Example'''
 
'''Example'''
* <code>MyLib\User\UserHelper</code> class must be located in <code>JPATH_LIBRARIES/src/MyLib/User/UserHelper.php</code></translate>
+
* ''MyLib\User\UserHelper'' class must be located in ''JPATH_LIBRARIES/src/MyLib/User/UserHelper.php''</translate>
  
 
<translate>
 
<translate>
 
=== Usage === <!--T:21-->
 
=== Usage === <!--T:21-->
 
</translate>
 
</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
// Tell the auto-loader to look for namespaced classes starting with MyLib in the JPATH_LIBRARIES/src directory
+
// Tell the autoloader to look for namespaced classes starting with MyLib in the JPATH_LIBRARIES/src directory
JLoader::registerNamespace('MyLib', JPATH_LIBRARIES . '/src');</source>
+
JLoader::registerNamespace('MyLib', JPATH_LIBRARIES . '/src');</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 91: Line 91:
 
</translate>
 
</translate>
 
<translate><!--T:23-->
 
<translate><!--T:23-->
To access our library from any place in the application, create a system plugin which will register our library with the JLoader. This plugin should fire on <code>onAfterInitialise</code> event:</translate>
+
To access our library from any place in the application, create a system plugin which will register our library with the JLoader. This plugin should fire on the ''onAfterInitialise'' event.</translate>
  
 
<translate>
 
<translate>
 
=== Manifest File === <!--T:24-->
 
=== Manifest File === <!--T:24-->
 
</translate>
 
</translate>
<source lang="xml">
+
<syntaxhighlight lang="xml">
 
<?xml version="1.0" encoding="utf-8"?>
 
<?xml version="1.0" encoding="utf-8"?>
 
<extension version="3.0" type="plugin" group="system" method="upgrade">
 
<extension version="3.0" type="plugin" group="system" method="upgrade">
Line 114: Line 114:
 
     </files>
 
     </files>
 
</extension>
 
</extension>
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
 
=== Plugin File === <!--T:25-->
 
=== Plugin File === <!--T:25-->
 
</translate>
 
</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
 
<?php
 
<?php
 
/**
 
/**
Line 146: Line 146:
 
     }
 
     }
 
}
 
}
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:26-->
 
<translate><!--T:26-->

Latest revision as of 17:12, 21 October 2022

Other languages:
Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎فارسی

There are several approaches to registering your own library with Joomla's autoloader and then use it in your extension. All these approaches are based on the JLoader class. For this tutorial, assume that your library is located in the /libraries/mylib folder.

Discovering Classes[edit]

Classes in a folder that follow a naming convention can be registered collectively with JLoader's discover() method. The discover method looks at the file names in a folder and registers classes based on those names. Additional arguments can be used to update the class register and recurse into sub-folders.

// Register all files in the /libraries/mylib folder as classes with a name like: MyLib<Filename>
JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');

This method works by following the special naming convention:

  • /mylib/user.php will be equal to MylibUser
  • /mylib/userhelper.php will be equal to MylibUserHelper

The Prefix Loader[edit]

Since Joomla Platform 12.1 (Joomla! CMS 3+), there is the ability to register where the autoloader will look based on a class prefix. (Previously only the J prefix was supported, bound to the /libraries/joomla folder.). This is done with the registerPrefix() method and allows for several scenarios:

  • A developer can register the prefix of custom classes and a root path to allow the autoloader to find them.
  • A developer can register an extra path for an existing prefix. (For example, this allows the Joomla CMS to have custom libraries but still using the J prefix.)
  • A developer can register a forced override for a prefix. This could be used to completely override the core classes with a custom replacement.

Convention[edit]

The class name must be in CamelCase and each segment of the name will represent a folder path where the last segment of the name is the name of the class file. If there is only one part to the class name, the autoloader will look for the file in a folder of the same name. Folder names must be in lower case.

Examples

  • PrefixUserModel class should be located in PATH_TO_PREFIX/user/model.php
  • PrefixUser class should be located in PATH_TO_PREFIX/user/user.php

Our scenario examples:

  • MylibUserHelper class should be located in /libraries/mylib/user/helper.php
  • MylibUser class should be located in /libraries/mylib/user/user.php

There is no limit to the depth to which the autoloader will search, providing it forms a valid path based on the CamelCase natural of the class name. Note that while acronyms and names such as HTML, XML and MySQL have a standard presentation in text, such terms should observe CamelCase rules programmatically. ("HTML" becomes "Html", "XML" becomes "Xml" and so on.)

Usage[edit]

// Tell the autoloader to look for classes starting with "Mylib" in a specific folder.
JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');
// Tell the autoloader to also look in the "/libraries/cms" folder for "J" prefixed classes.
JLoader::registerPrefix('J', JPATH_PLATFORM . '/cms');
// Tell the autoloader to reset the "J" prefix and point it to a custom fork of the platform.
JLoader::registerPrefix('J', '/my/platform/fork', true);

Note on registerPrefix[edit]

For Joomla CMS 2.5, the prefix cannot start with the same letter. The system will try to load the first matched. For example, if we register prefix JM, as J prefix exists, the JLoader will find J prefix. When it searches for the class in the registered path of J, no class will be found.

Namespace Loader[edit]

As of Joomla CMS v3.1.2, the core autoloader has support for autoloading PSR-0 style namespaced libraries. (You can study PHP namespaces here.) If you only support Joomla on PHP 5.3+ (which you do if you only support Joomla CMS v3.x or greater), you can utilize code that uses native PHP namespaces. In accordance with PSR-0 rules, the directory and file casing must match that of the PHP namespace and class.

Example

  • MyLib\User\UserHelper class must be located in JPATH_LIBRARIES/src/MyLib/User/UserHelper.php

Usage[edit]

// Tell the autoloader to look for namespaced classes starting with MyLib in the JPATH_LIBRARIES/src directory
JLoader::registerNamespace('MyLib', JPATH_LIBRARIES . '/src');

Accessing the Library from Anywhere[edit]

To access our library from any place in the application, create a system plugin which will register our library with the JLoader. This plugin should fire on the onAfterInitialise event.

Manifest File[edit]

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.0" type="plugin" group="system" method="upgrade">
    <name>System - Mylib</name>
    <author>Joomla! Project</author>
    <creationDate>March 2013</creationDate>
    <copyright>Copyright (C) 2005 - 2013 Open Source Matters. All rights reserved.</copyright>
    <license>GNU General Public License version 2 or later.</license>
    <authorEmail>admin@joomla.org</authorEmail>
    <authorUrl>www.joomla.org</authorUrl>
    <version>1.0.0</version>
    <description>Simple example plugin to register custom library.</description>

    <files>
        <filename plugin="mylib">mylib.php</filename>
        <filename>index.html</filename>
    </files>
</extension>

Plugin File[edit]

<?php
/**
 * @copyright   Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later.
 */

defined('_JEXEC') or die;

/**
 * Mylib plugin class.
 *
 * @package     Joomla.plugin
 * @subpackage  System.mylib
 */
class plgSystemMylib extends JPlugin
{
    /**
     * Method to register custom library.
     *
     * return  void
     */
    public function onAfterInitialise()
    {
        JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');
    }
}

Now you will be able to call classes from your library (located in /libraries/mylib) from any component, module or plugin.