简体   繁体   中英

How to use Dependency Injection on Yii2

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

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

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

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 syntax error, unexpected 'Servico' (T_STRING), expecting variable (T_VARIABLE)

at this line

public Servico $servicoModel;

What I am doing wrong?

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;

EDIT.

Change your __construct to this:

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

Your errors:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM