如何在Yii2上使用依赖注入

时间:2015-02-26 21:37:46

标签: php dependency-injection yii2

我是Yii2的新手,我正在尝试使用依赖注入

在我的场景中, Pedido 可以有一个 Servico ,而Servico有很多Pedidos。这是 Pedido 类模型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "pedido".
 *
 * @property integer $id
 * @property string $data
 * @property integer $servico_id
 *
 * @property Servico $servico
 */
class Pedido extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'pedido';
    }

    public function rules()
    {
        return [
            [['data', 'servico_id'], 'required'],
            [['data'], 'safe'],
            [['servico_id'], 'integer']
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'data' => Yii::t('app', 'Data'),
            'servico_id' => Yii::t('app', 'Servico ID'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getServico()
    {
        return $this->hasOne(Servico::className(), ['id' => 'servico_id']);
    }
}

这是 Servico 模型类

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "servico".
 *
 * @property integer $id
 * @property string $descricao
 * @property string $valor
 * @property integer $quantidade
 *
 * @property Pedido[] $pedidos
 */
class Servico extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'servico';
    }


    /**
     * @inheritdoc

     */
    public function rules()
    {
        return [
            [['descricao', 'valor'], 'required'],
            [['valor'], 'number'],
            [['quantidade'], 'integer'],
            [['descricao'], 'string', 'max' => 1000]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'descricao' => Yii::t('app', 'Descrição'),
            'valor' => Yii::t('app', 'Valor'),
            'quantidade' => Yii::t('app', 'Quantidade'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPedidos()
    {
        return $this->hasMany(Pedido::className(), ['servico_id' => 'id']);
    }
}

在我的 PedidoController 课程中,我想要注入 Servico 课程。我创建了 construtor 并以这种方式更改了 actionCreate

    <?php
    namespace app\controllers;

    use Yii; 
    use app\models\Pedido; 
    use app\models\Servico; 
    use app\models\PedidoSearch; 
    use yii\web\Controller; 
    use yii\web\NotFoundHttpException; 
    use yii\filters\VerbFilter; 
    use yii\di\Container;

    /** * PedidoController implements the CRUD actions for Pedido model. */  
  class PedidoController extends Controller {

    public Servico $servicoModel;

    public function __construct(Servico $servicoModel, $config = [])
    {
        $this->$servicoModel = $servicoModel;
        parent::__construct($config);
    }



    public function actionCreate()
    {

        $model = new Pedido();

        // 
        $container = new Container();
        $container->set('servico', 'app\models\Servico');
        $servicoModel = $container->get('servico');


        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    }

但是当我在索引操作上遇到这个错误时:

  

PHP Parse Error - yii \ base \ ErrorException语法错误,意外   &#39; Servico&#39; (T_STRING),期待变量(T_VARIABLE)

在这一行

  

public Servico $ servicoModel;

我做错了什么?

1 个答案:

答案 0 :(得分:8)

你的错误与DI无关。错误在此行:public Servico $servicoModel;。您是以Java样式编写的,而不是PHP。改为:

public $servicoModel = null;

EDIT。

将您的__construct更改为:

public function __construct($id, $module, Servico $servicoModel, $config = [])
    {
        $this->servicoModel = $servicoModel;
        parent::__construct($id, $module, $config);
    }

您的错误:

1)$this->$servicoModel对象属性写了$this->VARIABLE_NAME,在VARIABLE_NAME之前没有使用$

2)在构造controller中,第一个和第二个参数是$id$module。见 - https://github.com/yiisoft/yii2/blob/master/framework/base/Controller.php#L77