netsells/interface-binder

一个简单的包,允许您使用PHP8属性将接口绑定到具体的类

1.0.1 2021-02-09 09:58 UTC

This package is auto-updated.

Last update: 2024-08-27 20:37:53 UTC


README

接口绑定器提供了一个简单的方法,可以在给定的目录数组中绑定接口到实现。

安装

使用composer

composer require netsells/interface-binder

然后使用以下 artisan 命令发布配置文件

php artisan vendor:publish --tag=interface-binder

用法

将您想要扫描接口的目录添加到 interface-binder.php 配置文件中的 directories 数组

return [
    /*
    |--------------------------------------------------------------------------
    | Directories to scan for interfaces
    |--------------------------------------------------------------------------
    |
    */

    'directories' => [
        app_path('Features'),
        app_path('Services'),
    ],
];

然后,您只需为要绑定的接口提供一个 BoundTo 属性,告诉 Binder 您希望将其绑定到哪个具体类

namespace App\Features\CodeVerifier;

use App\Models\User;

#[BoundTo(UserCodeVerifier::class)]
interface UserCodeVerifierInterface
{
    public function verifyUserCode(User $user, string $codeGiven): bool;
}

该类由以下具体类实现

namespace App\Features\CodeVerifier;

use App\Models\User;

class UserCodeVerifier implements UserCodeVerifierInterface
{
    public function verifyUserCode(User $user, string $codeGiven): bool
    {
        return true;
    }
}

这就是全部!当您尝试从容器中解析 UserCodeVerifierInterface 时,您将得到一个 UserCodeVerifier 的实例。