'Get model by table name in yii2

I have one method in several models, implemented in different ways. I only know the name of table in database. I must find model of this table. How to do?

interface BaseIndexedModel
{
    public function writeSometext();
}

and some models implement it. Example

class First extends \yii\db\ActiveRecord implements BaseIndexedModel
{
    public function writeSometext(){
       return "1";
    }
}

class Second extends \yii\db\ActiveRecord implements BaseIndexedModel
{
    public function writeSometext(){
       return "2";
    }
}

Next on a certain event I need to call the desired model and this method. But when I call, I will only know the database table, but not the model.

If table "first", First::writeSometext(); If table "second", Second:: writeSometext();



Solution 1:[1]

You can do it this way when you get the table name

public function getModelName($table_name) {
    $table_name = 'first_table';  
    // $table_name = 'first';// if name is single word then comment the next line
    $table_split = explode("_",$table_name);
    $model = ucfirst($table_split[0]).ucfirst($table_split[1]);
    return $model;
}

you can call this function and check if it exists

$model = getModelName($table_name);
var_dump($model);

Solution 2:[2]

This one allows you to have 1+ words in the table name. In contrast to the solution posted by Ahmed Sunny, which only works for 2 words.

public function getModelName($tableName) {
    $tableSplit = explode("_",$ruleTableName);
    $className = '';

    foreach ($tableSplit as $word){
        $className .= ucfirst($word);
    }

    return $className;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmed Sunny
Solution 2 Alfred Landik