如何解决自定义包存储库接口在 Laravel 6 中不可实例化
目标 [MyPackage\Crm\App\Repositories\CommentRepositoryInterface]
在构建 [MyPackage\Crm\App\Http\CommentController]
时不可实例化。
如果我将存储库作为对象注入,则有问题的控制器 MyPackage\Crm\App\Http\CommentControllers.PHP
工作正常
public function __construct( \MyPackage\Crm\App\Repositories\CommentRepository\CommentRepository $commentRepository )
{
$this->noteRepo = $commentRepository;
}
但是如果我尝试注入 CommentRepositoryInterface 就会崩溃。
public function __construct( \MyPackage\Crm\App\Repositories\CommentRepository\CommentRepositoryInterface $commentRepository )
{
$this->noteRepo = $commentRepository;
}
我的配置/app.PHP
return [
MyPackage\Crm\App\CommentServiceProvider::class
]
Composer.json
"MyPackage\\Crm\\": "packages/mypackage/crm/src"
界面
namespace MyPackage\Crm\App\Repositories;
{
interface CommentRepositoryInterface
{
public function create( int $userId );
}
}
仓库类
namespace MyPackage\Crm\App\Repositories;
class CommentRepository implements CommentRepositoryInterface
{
public function create(int $userId)
{
// Todo: Implement create() method.
}
.....
}
我的自定义包提供程序类
namespace MyPackage\Crm\App;
use Illuminate\Support\ServiceProvider;
use MyPackage\Crm\App\Repositories\CommentRepositoryInterface;
use MyPackage\Crm\App\Repositories\CommentRepository;
class CommentServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
include __DIR__.'/routes.PHP';
}
public function register()
{
$this->app->make('MyPackage\Crm\App\Http\CommentController');
$this->app->bind(CommentRepositoryInterface::class,CommentRepository::class);
}
}
PHP artisan clear-compiled
不会修复任何东西并抛出不可实例化的错误
解决方法
取出
$this->app->make('MyPackage\Crm\App\Http\CommentController');
从提供者注册方法解决问题。
工作提供者代码:
namespace MyPackage\Crm\App;
use Illuminate\Support\ServiceProvider;
use MyPackage\Crm\App\Repositories\CommentRepositoryInterface;
use MyPackage\Crm\App\Repositories\CommentRepository;
class CommentServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
include __DIR__.'/routes.php';
}
public function register()
{
$this->app->bind(CommentRepositoryInterface::class,CommentRepository::class);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。