4

I have a question about the SetupInterface method getTable($tableName).

What is its role? Why should I use this method instead of using directly the name of the table I want to work on?

Is it in case I need to work on differents databases?

1 Answer 1

6

Is it in case I need to work on differents databases?

Definitely not

What is its role? Why should I use this method instead of using directly the name of the table I want to work on?

The reason is because Magento supports table prefixes out of the box. This is the main purpose of this method, as if you work on a database with table prefixes then calling the original table name directly will break your code.

FYI, here's the implementation of that method:

public function getTable($tableName, $connectionName = ResourceConnection::DEFAULT_CONNECTION)
{
    $cacheKey = $this->_getTableCacheName($tableName);
    if (!isset($this->tables[$cacheKey])) {
        $this->tables[$cacheKey] = $this->resourceModel->getTableName($tableName, $connectionName);
    }
    return $this->tables[$cacheKey];
}

And if you check the getTableName from the resource model:

public function getTableName($modelEntity, $connectionName = self::DEFAULT_CONNECTION)
{
    $tableSuffix = null;
    if (is_array($modelEntity)) {
        list($modelEntity, $tableSuffix) = $modelEntity;
    }

    $tableName = $modelEntity;

    $mappedTableName = $this->getMappedTableName($tableName);
    if ($mappedTableName) {
        $tableName = $mappedTableName;
    } else {
        $tablePrefix = $this->getTablePrefix();
        if ($tablePrefix && strpos($tableName, $tablePrefix) !== 0) {
            $tableName = $tablePrefix . $tableName;
        }
    }

    if ($tableSuffix) {
        $tableName .= '_' . $tableSuffix;
    }
    return $this->getConnection($connectionName)->getTableName($tableName);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.