我有一些artisan命令来执行一些CLI逻辑。
class SyncFooCommand extends AbstractBaseSyncCommand
class SyncBarCommand extends AbstractBaseSyncCommand
class SyncBazCommand extends AbstractBaseSyncCommand每个artisan命令都会扩展abstract class AbstractBaseSyncCommand extends Command implements SyncInterface。
多亏了这一点,我可以在抽象的父类中加入一些共享的逻辑。
我注入了Carbon或FileSystem,两者都在孩子们的班级里工作得像个魔法师。
<?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,我就会得到:
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很简单,不需要做任何绑定。我遗漏了什么?
总结一下:
$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发布于 2018-10-17 15:46:09
也许你的应用程序应该知道如何检索它?喜欢
$this->app->bind('SomeAbstraction', function ($app) {
return new Implementation();
});https://stackoverflow.com/questions/52847878
复制相似问题