PHP code example of mrclay / props-dic

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

    

mrclay / props-dic example snippets


/**
 * @property-read Foo $foo
 * @method        Foo new_foo()
 */
class MyContainer extends \Props\Container {
    public function __construct() {
        $this->foo = function (MyContainer $c) {
            return new Foo();
        };
    }
}

$c = new MyContainer();

$foo1 = $c->foo; // your IDE knows this is a Foo instance

$foo2 = $c->new_foo(); // A fresh Foo instance

$foo3 = $c->foo; // same as $foo1

/**
 * @property-read string $style
 * @property-read Dough  $dough
 * @property-read Cheese $cheese
 * @property-read Pizza  $pizza
 * @method        Slice  new_slice()
 */
class PizzaServices extends \Props\Container {
    public function __construct() {
        $this->style = 'deluxe';

        $this->dough = function (PizzaServices $c) {
            return new Dough();
        };

        $this->setFactory('cheese', 'CheeseFactory::getCheese');

        $this->pizza = function (PizzaServices $c) {
            $pizza = new Pizza($c->style, $c->cheese);
            $pizza->setDough($c->dough);
            return $pizza;
        };

        $this->slice = function (PizzaServices $c) {
            return $c->pizza->getSlice();
        };
    }
}

$c = new PizzaServices;

$c->pizza; // This first resolves and caches the cheese and dough.

$c->pizza; // The same pizza instance as above (no factories called).

$c->new_slice(); // a new Slice instance
$c->new_slice(); // a new Slice instance

$c->aaa = new AAA();

$c->bbb = function ($c) {
    return BBB::factory($c);
};

$c->setFactory('bbb', 'BBB::factory');

$c->bbb === $c->bbb; // true

$c->new_bbb() === $c->new_bbb(); // false

// store a value
$c->ccc = new CCC();
$c->hasFactory('ccc'); // false

// store a factory
$c->ccc = function () {
    return new CCC();
};
$c->hasFactory('ccc'); // true

$callable = $c->getFactory('ccc');

$c->foo = function ($c) {
    return new Foo($c->bar);
};

$c->extend('foo', function ($value, Container $c) {
    return array($value, $c->bing);
});

$c->foo; // [Foo, "bing"]

$c->new_foo(); // re-call original foo factory and re-extend output (`bar` and `bing` will be re-read)