首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 5.7:我向构造函数中注入了bunch on类,但constructor \Csv\Reader是唯一一个不能工作的

Laravel 5.7:我向构造函数中注入了bunch on类,但constructor \Csv\Reader是唯一一个不能工作的
EN

Stack Overflow用户
提问于 2018-10-17 13:35:42
回答 1查看 73关注 0票数 0

我有一些artisan命令来执行一些CLI逻辑。

代码语言:javascript
复制
class SyncFooCommand extends AbstractBaseSyncCommand
class SyncBarCommand extends AbstractBaseSyncCommand
class SyncBazCommand extends AbstractBaseSyncCommand

每个artisan命令都会扩展abstract class AbstractBaseSyncCommand extends Command implements SyncInterface

多亏了这一点,我可以在抽象的父类中加入一些共享的逻辑。

我注入了Carbon或FileSystem,两者都在孩子们的班级里工作得像个魔法师。

代码语言:javascript
复制
<?php

namespace App\Console\Commands\Sync;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\Factory as Filesystem;
use League\Csv\Reader;

abstract class AbstractBaseSyncCommand extends Command implements SyncInterface
{
    protected $carbon;
    protected $fileSystem;
    protected $reader;

    public function __construct(
        Carbon $carbon,
        FileSystem $fileSystem,
        Reader $reader
    ) {
        parent::__construct();

        $this->carbon = $carbon; // works like a charm
        $this->fileSystem = $fileSystem; // works like a charm
        $this->reader = $reader; // fails, why?
    }
}

SyncWhateverCommand中,我可以很容易地调用和使用$this->carbon$this->fileSystem,但只要它命中$this->reader,我就会得到:

代码语言:javascript
复制
   Illuminate\Contracts\Container\BindingResolutionException  : Target [League\Csv\Reader] is not instantiable while building [App\Console\Commands\Sync\SyncFooCommand].

  at /home/vagrant/code/foo/vendor/laravel/framework/src/Illuminate/Container/Container.php:945
    941|         } else {
    942|             $message = "Target [$concrete] is not instantiable.";
    943|         }
    944|
  > 945|         throw new BindingResolutionException($message);
    946|     }
    947|
    948|     /**
    949|      * Throw an exception for an unresolvable primitive.

怎么了?The installation很简单,不需要做任何绑定。我遗漏了什么?

总结一下:

代码语言:javascript
复制
$csv = $this->reader->createFromPath($path, 'r'); // fails, but I want to use it this way

$csv = Reader::createFromPath($path, 'r'); // works but I don't want facades because they look ugly
EN

回答 1

Stack Overflow用户

发布于 2018-10-17 15:46:09

也许你的应用程序应该知道如何检索它?喜欢

代码语言:javascript
复制
$this->app->bind('SomeAbstraction', function ($app) {
    return new Implementation();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52847878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档