PHP code example of romeoz / rock-di

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

    

romeoz / rock-di example snippets


namespace test;

use rock\di\Container;

class Foo 
{
    
}

$config = [
    'class' => '\test\Foo', 
    // 'singleton' => true,   // if you want to return singleton
 ];
$alias = 'foo' ;  // short alias
Container::register($alias, $config);

$foo = Container::load('foo');

namespace test;

use rock\di\Container;

class Foo 
{
    
}

class Bar 
{
    public $foo;
        
    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

$config = [
    'class' => '\test\Foo',
 ];
Container::register('foo' , $config);

$config = [
    'class' => '\test\Bar',
 ];
Container::register('bar' , $config);

$bar = Container::load('bar');
$bar->foo instanceof Bar; // output: true

namespace test;

use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;

class Foo implements ObjectInterface
{
    use ObjectTrait;
    
    public $name;
}

$config = [
    'class' => '\test\Foo', 
    
    // properties
    'name' => 'Tom'
 ];

Container::register('foo', $config);

$foo = Container::load('foo');

echo $foo->name; // output: Tom 

namespace test;

use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;

class Foo implements ObjectInterface
{
    use ObjectTrait;
    
    private $name;
    
    public function setName($name)
    {
        $this->name = $name;
    }
    
    public function getName()
    {
        return $this->name;
    }
    
}

$config = [
    'class' => '\test\Foo', 
    
    // properties
    'name' => 'Tom'
 ];

Container::register('foo', $config);

$foo = Container::load('foo');

echo $foo->name; // output: Tom