在Yii2中动态声明模型

时间:2016-03-03 04:14:31

标签: yii2 yii2-advanced-app

我想动态创建模型的实例。是否可以使用yii2?

我正在尝试这样的事情

    <?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是模型的名称。当我尝试这个时,我得到一个像这样的错误

  

语法错误,意外的'$ model_name'(T_VARIABLE),期待   标识符(T_STRING)

2 个答案:

答案 0 :(得分:1)

我将无法对此进行测试(我在手机上),但您可以尝试这样做:

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.');
    }
}

答案 1 :(得分:0)

您可以尝试这种方式:

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.');
    }
}

注意:仅适用于当前命名空间。