biladina
biladina

Reputation: 147

Yii2 - How to call ActiveRecord method given its name

I have a string variable that contains the model's class name, and I want to call a method on said model using that variable, is that possible??

My code:

foreach($tables as $tables)
{
    $table = ArrayHelper::getValue($tables, 'table_name');
    $model = \common\models\$table::findAll();
    var_dump($model);
}

A simpler version:

$table = "DataAnalysis";
$model = \common\models\$table::findAll();
var_dump($model);

When I run that code, I get the following error:

Exception 'ParseError' with message 'syntax error, unexpected '$table' (T_VARIABLE), expecting identifier (T_STRING)'

Is there anything I can do to call model given the string contained in the variable?

Upvotes: 0

Views: 132

Answers (2)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

You should simply do,

$model="\\common\\models\\DataAnalysis";
$model::findAll();

OR

$table="DataAnalysis"; 
$model="\\common\\models\\{$table}"; 
$model::findAll();

rather than call_user_func() thats too much code for a simple task

Edit

If you need to instantiate the class instead of static call, you can simply do

$table="DataAnalysis"; 
$model="\\common\\models\\{$table}"; 
new $model();

Upvotes: 2

Raul Sauco
Raul Sauco

Reputation: 2705

You can do it using call_user_func().

// If you have the name of the ActiveRecord class, like in you comment
$class = 'DataAnalysis';

/** @var ActiveQuery $query */
$query = call_user_func($class . '::find');

// Then use the query as you want
foreach($query->each() as $model) {
    // Do something with your model
}

If you are not sure if the value in the variable will always be correct, wrap it on a try/catch.

If what you have is the table name, and not the class name, you can try to convert with the Yii inflector camelize method.

use yii\helpers\Inflector;

$tableName = 'some_snake_case_name';
$className = Inflector::camelize($tableName);
/** @var ActiveQuery $query */
$query = call_user_func($className . '::find');

// If you want to filter results
$query->where(...);

// Then use the query as you want
foreach($query->each() as $model) {
    // Do something with your model
}

call_user_function docs are here.

Upvotes: 1

Related Questions