Reputation: 2966
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
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
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