PHP code example of siganushka / registry-contracts

1. Go to this page and download the library: Download siganushka/registry-contracts library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

siganushka / registry-contracts example snippets


// ./src/Channel/ChannelInterface.php

interface ChannelInterface
{
    public function methodA(): string;
    public function methodB(): int;
 
    // ...
}

// ./src/Channel/FooChannel.php

class FooChannel implements ChannelInterface
{
    // ...
}

// ./src/Channel/BarChannel.php

class BarChannel implements ChannelInterface
{
    // ...
}

use Siganushka\Contracts\Registry\ServiceRegistry;

$registry = new ServiceRegistry(ChannelInterface::class);
$registry->register('foo', new FooChannel());
$registry->register('bar', new BarChannel());

$registry->get('foo');      // return instanceof FooChannel
$registry->has('bar');      // return true
$registry->all();           // return array of instanceof ChannelInterface
$registry->getServiceIds(); // return ['foo', 'bar']

// ./src/Channel/FooChannel.php

use Siganushka\Contracts\Registry\ServiceRegistry;
use Siganushka\Contracts\Registry\AliasableInterface;

class FooChannel implements ChannelInterface, AliasableInterface
{
    public function getAlias(): string
    {
        return 'foo';
    }

    // ...
}

$channels = [
    new FooChannel()
];

// the second argument is type iterable of $services 
$registry = new ServiceRegistry(ChannelInterface::class, $channels);

$registry->get('foo');      // return instanceof FooChannel
$registry->has('foo');      // return true
$registry->all();           // return array of instanceof ChannelInterface
$registry->getServiceIds(); // return ['foo']

// ./src/Channel/ChannelRegistry.php

class ChannelRegistry extends ServiceRegistry
{
    public function __construct(iterable $channels)
    {
        parent::__construct(ChannelInterface::class, $channels);
    }
}

// ./src/Controller/BazController.php

class BazController extends AbstractController
{
    public function index(ChannelRegistry $registry)
    {
        $foo = $registry->get(FooChannel::class);
        // or $registry->get('foo') if using alias
        // $foo is instanceof FooChannel
    }
}