0

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?

2
  • This has nothing to do with DI Commented Feb 27, 2015 at 8:57
  • Thanks for the comment. How should I inject the Servico class in the PedidoController class ? Commented Feb 27, 2015 at 13:35

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I changed the line to public $servicoModel = null; as you said. But now I am getting this error *PHP Recoverable Error – yii\base\ErrorException Argument 1 passed to app\controllers\PedidoController::__construct() must be an instance of app\models\Servico, string given What should I do?
Thanks a lot for your help. The error is not happening anymore

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.