代码之家  ›  专栏  ›  技术社区  ›  Murlidhar Fichadia

php-laravel中正确的依赖注入方法

  •  0
  • Murlidhar Fichadia  · 技术社区  · 6 年前

    我有一个日志类,如下所示,我想将下面的类注入我的控制器并生成一个日志:

    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测试控制器

    <?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);
    

    如果我正在使用依赖注入,我应该如何做上述?

    我可以做到如下:

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

    但我想避免使用新的。

    我想做什么。

    $this->log($parameters)->create();
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   ZeroOne    6 年前
    1. 你可以这样做。 $this->log->create(parameters);
    2. 创建方法链接ex: $this->log->setData($parameters)->create();