接口的依赖注入

时间:2017-01-25 15:03:13

标签: php laravel oop dependency-injection interface

嗨,我收到的错误应该是接口的实例

App\Repositories\Traits\PhotoService::__construct() must be an instance of AwsServiceInterface, instance

这是我到目前为止所拥有的

namespace App\Repositories\Interfaces;

interface AwsServiceInterface
{
 //...
}

现在我有了这个课程

namespace App\Repositories\Interfaces;

use App\Repositories\Interfaces\AwsServiceInterface;

class CloudFrontService implements AwsServiceInterface
{

    public function __construct()
   {
   }
}

现在我在这个类上使用依赖注入

namespace App\Repositories\Traits;

use App\Repositories\Interfaces\AwsServiceInterface;

class PhotoService
{
    protected $service;

    public function __construct(AwsServiceInterface $service)
    {
        $this->service = $service;
    }

    public function getAuthParams($resource, $search_key = '')
    {
        // Execute a function from a class that implements AwsServiceInterface
    }

我正在调用PhotoService类

$photo_service = new PhotoService(new CloudFrontService());
echo $photo_service->getAuthParams($resource);

但不知怎的,我收到了这个错误

FatalThrowableError: Type error: Argument 1 passed to App\Repositories\Traits\PhotoService::__construct() must be an instance of AwsServiceInterface, instance of App\Repositories\Interfaces\CloudFrontService given

4 个答案:

答案 0 :(得分:1)

您遇到了命名空间问题。您正在使用的类型提示并不完整。

只是猜测,但我认为您要将typehint更改为:

 public function __construct(App\Repositories\Interfaces\AwsServiceInterface $service)

http://php.net/manual/en/language.namespaces.basics.php

答案 1 :(得分:1)

App\Providers\AppServiceProvider课程中,在register()方法中添加以下代码:

$this->app->bind(
    'App\Repositories\Interfaces\AwsServiceInterface',
    'App\Repositories\Interfaces\CloudFrontService'
);

然后您可以将其用作:

$photo_service = app(PhotoService::class);
echo $photo_service->getAuthParams($resource);

答案 2 :(得分:0)

您需要将实现绑定到该接口。 Here's一个例子。

Laravel本身并不知道您要为此接口使用什么实现,您需要自己指定。

答案 3 :(得分:-1)

我解决了我的问题。对于那些有相同问题的人,请确保执行此步骤。 1.如@Amit所述,在服务提供者上仔细检查服务是否在寄存器功能下绑定 2.确保

  • php artisan clear-compile
  • php artisan cache:clear
  • php artisan config:clear