PHP code example of paket / bero

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

    

paket / bero example snippets


$bero = new \Paket\Bero\MinimalBero();

$bero = new \Paket\Bero\StrictBero();

class A
{
}

class B
{
    public $a;

    public function __construct(A $a) 
    {
        $this->a = $a;
    }
    
    public function doStuff(): int
    {
        return 17;
    }
}

$b = $bero->getObject(B::class);
assert(is_object($b->a));
$b->doStuff();

$int = $bero->callCallable(function (A $a, B $b) {
    assert($a === $b->a);
    return $b->doStuff();
});
assert($int === 17);

$bero->addObject(A::class, $a);
$b = $bero->getObject(B::class);
assert($a === $b->$a);

$bero->addCallable(B::class, function (A $a) {
    return new B($a);
});
$b = $bero->getObject(B::class);

class C 
{
    public function __construct(int $i)
    {
    }
}

$bero->addCallable(C::class, function () {
    return new C(17);
});

interface I 
{
}

class D implements I 
{
}

$bero->addInterface(I::class, D::class);
$i = $bero->getObject(I::class);
assert($i instanceof D);

interface Service
{
    public function doStuff(): void;
}

class FooService implements Service
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function doStuff(): void
    {
    }
}

class BarService implements Service
{
    public function doStuff(): void
    {
    }
}

class Controller
{
    private $bero;

    public function __construct(Bero $bero)
    {
        $this->bero = $bero;
    }
    
    public function run(bool $flag)
    {
        if ($flag) {
            $service = $this->bero->getObject(FooService::class);
        } else {
            $service = $this->bero->getObject(BarService::class);
        }
        $service->doStuff();
    }
}

$bero->addObject(Bero::class, $bero); // <-- self aware
$bero->addObject(A::class, $a);
$c = $bero->getObject(Controller::class);
$c->run(true);

$bero = new StrictBero();
$bero->callCallable(function (ArticleRepository $articleRepository, Json $json) {
   $article = $articleRepository->getArticleById(17);
   echo $json->encode($article);
});