PHP code example of opxcore / container

1. Go to this page and download the library: Download opxcore/container 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/ */

    

opxcore / container example snippets


class Controller
{
    protected Repository $repository;
    
    public function __construct(Repository $repository)
    {
        $this->repository = $repository;
    }
}

$container = Container::setContainer(new Container);

$container = Container::getContainer();

$container->bind($abstract, $concrete, $parameters);

$container->bind('logger', Logger::class);

// New instance of Logger with resolved dependencies will be retuened.
$logger = $container->make('logger');

class Controller
{
    protected RepositoryInterface $repository;
    
    public function __construct(RepositoryInterface $repository)
    {
        $this->repository = $repository;
    }
}

class FileRepository implements RepositoryInterface
{
    protected string $path;
    
    public function __construct(string $path)
    {
        $this->path = $path;
    }
}

$container->bind(RepositoryInterface::class, FileRepository::class, ['path'=>'/data/storage']);

$controller = $container->make(Controller::class);

// When FileRepository dependencies would be resolving, given value would be passed to `path` attribute.
$container->bindParameters(FileRepository::class, ['path' => '/data/storage']);

// When Controller would be resolved a FileRepository would be given as RepositoryInterface dependency.
$container->bindParameters(Controller::class, [RepositoryInterface::class => FileRepository::class]);

$container->singleton(RepositoryInterface::class, FileRepository::class, ['path'=>'/data/storage']);

// Each time when RepositoryInterface needs to be resolved
// the same instance of FileRepository would be given.
$repository = $container->make(RepositoryInterface::class);

$container->singleton(RepositoryInterface::class, FileRepository::class, ['path'=>'/data/storage']);
$container->alias(RepositoryInterface::class, 'repo');

// This would return FileRepository instance.
$container->make('repo');

$container->instance('path', '/data/storage');
// '/data/storage' would be returned
$container->make('path');

$container->instance(RepositoryInterface::class, new FileRepository('/data/storage'));
// FileRepository would be returned
$container->make(RepositoryInterface::class);

$container->bind(RepositoryInterface::class, FileRepository::class);
$container->make(RepositoryInterface::class, ['path'=>'/data/storage']);