简体   繁体   English

依赖注入在PHP中的正确方法-Laravel

[英]Dependency Injection the right way in Php - Laravel

I have a log class as below and I would like to inject below class to my controller and make a log: 我有一个如下所示的日志类,我想将以下类注入到我的控制器中并进行日志:

Log.php Log.php

<?php

namespace App\Helpers;

use DB;


class Log {

    private $tableName;
    private $tableId;
    private $tableIdVal;
    private $step;
    private $status;
    private $error;

    public function __construct($logTableName, $logTableId, $logTableIdVal, $step, $status, $error = null) {

        $this->tableName = $logTableName;
        $this->tableId   = $logTableId;
        $this->tableIdVal= $logTableIdVal;
        $this->step      = $step;
        $this->status    = $status;
        $this->error     = $error;

    }

    protected function create() {

        DB::table($this->tableName)->insert(
            [
                $this->tableId  =>  $this->tableIdVal,
                'step'          =>  $this->step,
                'error'         =>  $this->error,
                'status'        =>  $this->status
            ]
        );
    }

}

Testcontroller.php Testcontroller.php

<?php

namespace App\Http\Controllers;

use App\Helpers\{Load, Log};
use App\Models\{Post, Raw, RawDetail};

use DB;

class DetailsController extends Controller
{
    private $file;
    private $log;

    public function __construct($record, Log $logger) {

        $this->file = $record;
        $this->log  = $logger;
    }

public function process() {

        //make a log (is this correct?) I think $this->log will find a log method in this file, which does not exist.
        //I want to simple make a call to the constructor and then call create method on it.
        $this->log('raw_logs', 'raw_id', $this->file->id, Raw::STEP_1, Raw::STATUS_1);

If I am using dependency injection how should I do the above? 如果我使用依赖注入,该如何做?

I can do it like below: 我可以像下面这样:

$log = new Log($all-params-here);
$log->create();

But I want to avoid using new. 但我要避免使用new。

What I want to do. 我想做的事。

$this->log($parameters)->create();
  1. You can do like @HtmHell said in the comment ex: $this->log->create(parameters); 您可以像@HtmHell一样在注释中说: $this->log->create(parameters);
  2. You create method chaining ex: $this->log->setData($parameters)->create(); 您可以创建方法链接,例如: $this->log->setData($parameters)->create();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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