在 Laravel 中实现模型接口

Implementing Interface on Model in Laravel

我有一个 Laravel 5 模型 Account 实现了 Interface.

我已经实现了 Interface 的所有方法,但是当我 运行 代码时,Laravel 抱怨模型没有实现接口。

以下错误

Account.php(型号)

<?php

namespace Abc\Accounts\Models;

use Abc\Accounts\Contracts\Accountlnterface;
use Illuminate\Database\Eloquent\Model;

class Account extends Model implements Accountlnterface {
....

在我的控制器中,我正在这样做

$account = Account::where('something', 'value')->first();

这个returns模型就好了

问题出在我将它传递给另一个 class 控制器时

$result = new Transaction($account, 5.00);

T运行动作文件

public function __construct(Accountlnterface $account, float $value = 0.00) 
{
    $this->account = $account;

t运行saction 构造函数正在寻找接口,但是 laravel 抱怨帐户没有实现它。

我不确定这段代码有什么问题。

来自 Laravel

的错误

Type error: Argument 1 passed to Abc....\Transaction::__construct() must be an instance of Abc\Accounts\Components\Accountlnterface, instance of Tymr\Plugins\Accounts\Models\Account given.

模型加载后我直接运行这段代码

        if($account instanceof AccountInterface)
            echo "working";
        else
            echo "fails";

当然失败了。

您需要在您的服务提供商之一中注册服务容器绑定,或者最好创建一个新的服务提供商。

它有助于Laravel了解用于您的界面的实现。

use Illuminate\Support\ServiceProvider;

class ModelsServiceProvider extends ServiceProvider {
      public function register()
      {
         $this->app->bind(
            'Abc\Accounts\Contracts\Accountlnterface',
            'Abc\Accounts\Models\Account'
         );
      }
}

app/config/app.php中,在可用的提供商下注册您的服务提供商。

'providers' => [
    ...
    'ModelsServiceProvider',
]