Bloodhound
Bloodhound

Reputation: 2966

Dynamic declaration of a model in Yii2

I want to create an instance of a model dynamically. Is this possible with yii2?

I am trying something like this

    <?php

namespace app\components;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException; 
use yii\web\NotFoundHttpException;


use app\models; 


class SintelComponent extends Component
{

public function find($model_name, $id) 
{
    $magic = __NAMESPACE__.'\\'.$model_name; //__NAMESPACE__ is a magic constant
    if (($model = $magic::findOne($id)) !== null) 
    {
        return $model;
    } 
    else 
    {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
}

$model_name is the name of the model. When i try this i get an error like this

syntax error, unexpected '$model_name' (T_VARIABLE), expecting identifier (T_STRING)

Upvotes: 0

Views: 870

Answers (2)

Insane Skull
Insane Skull

Reputation: 9368

You can try this way:

namespace app\models; 
public function find($model_name, $id) 
{
    $magic = __NAMESPACE__.'\\'.$model_name; //__NAMESPACE__ is a magic constant
    if (($model = $magic::findOne($id)) !== null) 
    {
        return $model;
    } 
    else 
    {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Note: Works for current namespace only.

Upvotes: 0

morcen
morcen

Reputation: 368

I will not be able to test this (I'm on my phone), but can you try doing it like this:

public function find($model_name, $id) 
{
    $_model = '\app\\models\\'.$model_name;
    if (($model = $_model::findOne($id)) !== null) 
    {
        return $model;
    } 
    else 
    {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Upvotes: 1

Related Questions