kbondurant/attribute-container

An attribute based container for league/container

1.0.0 2022-02-25 22:48 UTC

This package is auto-updated.

Last update: 2024-04-26 03:16:51 UTC


README

An attribute based container for league/container.

Installation

Via Composer

composer require kbondurant/attribute-container

Requirements

The following versions of PHP are supported by this version.

  • PHP 8.0
  • PHP 8.1

Usage

This container allows you to bind an interface to its implementation using PHP Attributes

Add AttributeContainer as a delegate container to your league/container

<?php 

declare(strict_types=1);

$container = new League\Container\Container();
$delegate  = new Kbondurant\AttributeContainer\AttributeContainer();

$container->delegate($delegate);

Regular binding

<?php

declare(strict_types=1);

namespace Tests\Fixtures;

use Kbondurant\AttributeContainer\BindTo;

#[BindTo(Bar::class)]
interface Foo
{
    //
}

Singleton binding

<?php

declare(strict_types=1);

namespace Tests\Fixtures;

use Kbondurant\AttributeContainer\BindTo;

#[BindTo(Bar::class, true)]
interface Foo
{
    //
}

Custom binding attribute

If you do not want to rely on the provided BindTo attribute you can create your own attribute class that implements BindingAttribute interface

#[Attribute]
class MyBindingAttribute implements Kbondurant\AttributeContainer\BindingAttribute
{
    /**
     * @param class-string $class
     */
    public function __construct(
        private string $class,
    ) {
    }

    public function getClass(): string
    {
        return $this->class;
    }

    public function isShared(): bool
    {
        return false;
    }
}

#[MyBindingAttribute(Bar::class)]
interface Foo
{
    //
}

Testing

Testing includes PHPUnit and PHPStan (Level 9).

$ composer test

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT