PHP code example of delights / box

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

    

delights / box example snippets


use Delights\Box\Container;

$container = new Container();

$container->bind('key', 'value');
echo $container->resolve('key'); // prints "value"

$container->bind(Crawler::class, function () {
    return new Crawler('f4dg65gd6fg465g');
});

$container->singleton(Connection::class, function () {
    return new Connection();
});

$container->bindToImplementation(CrawlerInterface::class, Crawler::class);
// same as
$container->bindToImplementation(CrawlerInterface::class, new Crawler);
// same as
$container->bindToImplementation(CrawlerInterface::class, function () {
    return new Crawler;
});

use Delights\Box\Container;
$container = new Container();

class SomeClass {}
$container->resolve(SomeClass::class); // returns an instance of "SomeClass" 

class SomeOtherClass {
    public function __construct(SomeClass $dep) {
        $this->dep = $dep;
    }
}
$container->resolve(SomeOtherClass::class); 
// returns an instance of "SomeOtherClass"
// with $this->dep set to an instance of "SomeClass"

class PostsRepository {
    public function all() {
        return ['My article'];    
    }
}

class PostController {
    public function index(PostsRepository $repository) {
        return $repository->all();    
    }
}

$container->call(PostController::class, 'index');
// This returns |'My article']

$container->closure(function (SomeClass $class) {
    return $class instanceof SomeClass;
}); // returns true

class Vec2 {
    protected int $x;
    protected int $y;

    public function __construct(int $x, int $y) {
        $this->x = $x;
        $this->y = $y;
    }
}
$container->resolve(Vec2::class, [
    'x' => 2,
    'y' => 4
]); // returns an instance of "Vec2" 

use Delights\Box\PersistentContainer;

PersistentContainer::getInstance();

use Delights\Box\PersistentContainer;

// instead of this
PersistentContainer::getInstance()->bind('some', 'thing');

// you can do that
PersistentContainer::bind('some', 'thing');