Back to Table class

Method getInstance

public static \Joomla\CMS\Table\Table|bool
getInstance
(mixed $type, mixed $prefix = 'JTable', mixed $config = array())
Static method to get an instance of a Table class if it can be found in the table include paths.
Parameters
  • string $type The type (name) of the Table class to get an instance of.
  • string $prefix An optional prefix for the table class name.
  • array $config An optional array of configuration values for the Table object.
Returns
  • \Joomla\CMS\Table\Table|bool A Table object if found or boolean false on failure.
Since
  • 1.7.0
Deprecated
  • 5.0
Class: Table
Project: Joomla

Method getInstance - Source code

/**
 * Static method to get an instance of a Table class if it can be found in the table include paths.
 *
 * To add include paths for searching for Table classes see Table::addIncludePath().
 *
 * @param   string  $type    The type (name) of the Table class to get an instance of.
 * @param   string  $prefix  An optional prefix for the table class name.
 * @param   array   $config  An optional array of configuration values for the Table object.
 *
 * @return  Table|boolean   A Table object if found or boolean false on failure.
 *
 * @since       1.7.0
 * @deprecated  5.0 Use the MvcFactory instead
 */
public static function getInstance($type, $prefix = 'JTable', $config = array())
{
    // Sanitize and prepare the table class name.
    $type = preg_replace('/[^A-Z0-9_\\.-]/i', '', $type);
    $tableClass = $prefix . ucfirst($type);
    // Only try to load the class if it doesn't already exist.
    if (!class_exists($tableClass)) {
        // Search for the class file in the JTable include paths.
        $paths = self::addIncludePath();
        $pathIndex = 0;
        while (!class_exists($tableClass) && $pathIndex < \count($paths)) {
            if ($tryThis = Path::find($paths[$pathIndex++], strtolower($type) . '.php')) {
                // Import the class file.
                include_once $tryThis;
            }
        }
        if (!class_exists($tableClass)) {
            /*
             * If unable to find the class file in the Table include paths. Return false.
             * The warning JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND has been removed in 3.6.3.
             * In 4.0 an Exception (type to be determined) will be thrown.
             * For more info see https://github.com/joomla/joomla-cms/issues/11570
             */
            return false;
        }
    }
    // If a database object was passed in the configuration array use it, otherwise get the global one from Factory.
    $db = $config['dbo'] ?? Factory::getDbo();
    // Check for a possible service from the container otherwise manually instantiate the class
    if (Factory::getContainer()->has($tableClass)) {
        return Factory::getContainer()->get($tableClass);
    }
    // Instantiate a new table class and return it.
    return new $tableClass($db);
}