如何在Yii2上使用依赖注入 [英] How to use Dependency Injection on Yii2

查看:190
本文介绍了如何在Yii2上使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new on Yii2 and I am trying to use Dependency Injection.

在我的情况下,是 Pedido 可以有一个 Servico ,而Servico有很多Pedidos。这是 Pedido 类模型:

In my scenario a Pedido can have one Servico and a Servico has many Pedidos. Here is the Pedido class model:

<?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 模型class

Here is Servico model class

<?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 类。我已经创建了一个构造器,并以此方式更改了 actionCreate

In my PedidoController class I want to Inject the Servico class. I have created a construtor and changed the actionCreate in this way:

    <?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,
            ]);
        }
    }

    }

但是,当我在索引操作中遇到此错误:

But when I got this error on the index action:


PHP Parse Error – yii\base\ErrorException语法错误,意外的
'Servico'(T_STRING),期望变量(T_VARIABLE)

PHP Parse Error – yii\base\ErrorException syntax error, unexpected 'Servico' (T_STRING), expecting variable (T_VARIABLE)

此行


公共Servico $ servicoModel;

public Servico $servicoModel;

我在做什么错了?

推荐答案

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

Your mistake is not related with DI. The error is in this line: public Servico $servicoModel;. You wrote it in Java style, not PHP. Change to this:

public $servicoModel = null;

编辑。

更改您的 __ 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之前。

1) $this->$servicoModel object property wrote $this->VARIABLE_NAME, no use $ before VARIABLE_NAME.

2)首先在构造控制器中第二个参数是 $ id $ module 。参见- https://github.com/yiisoft/yii2/blob/master/ framework / base / Controller.php#L77

2) In construct controller first and second parameters is $id, $module. See - https://github.com/yiisoft/yii2/blob/master/framework/base/Controller.php#L77

这篇关于如何在Yii2上使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆