Back to Factory class

Method getContainer

public static \Joomla\DI\Container
getContainer
()
Get a container object
Returns
  • \Joomla\DI\Container
Since
  • 4.0.0
Class: Factory
Project: Joomla

Method getContainer - Source code

/**
 * Get a container object
 *
 * Returns the global service container object, only creating it if it doesn't already exist.
 *
 * This method is only suggested for use in code whose responsibility is to create new services
 * and needs to be able to resolve the dependencies, and should therefore only be used when the
 * container is not accessible by other means.  Valid uses of this method include:
 *
 * - A static `getInstance()` method calling a factory service from the container,
 *   see `Joomla\CMS\Toolbar\Toolbar::getInstance()` as an example
 * - An application front controller loading and executing the Joomla application class,
 *   see the `cli/joomla.php` file as an example
 * - Retrieving optional constructor dependencies when not injected into a class during a transitional
 *   period to retain backward compatibility, in this case a deprecation notice should also be emitted to
 *   notify developers of changes needed in their code
 *
 * This method is not suggested for use as a one-for-one replacement of static calls, such as
 * replacing calls to `Factory::getDbo()` with calls to `Factory::getContainer()->get('db')`, code
 * should be refactored to support dependency injection instead of making this change.
 *
 * @return  Container
 *
 * @since   4.0.0
 */
public static function getContainer() : Container
{
    if (!self::$container) {
        self::$container = self::createContainer();
    }
    return self::$container;
}