romeoz/rock-di

Small and flexible Dependency Injection library for PHP

0.14.0 2015-11-09 06:34 UTC

This package is not auto-updated.

Last update: 2024-12-17 05:17:35 UTC


README

Latest Stable Version Total Downloads Build Status HHVM Status Coverage Status License

Features

  • Service locator
  • Constructor injection
  • Support singleton
  • Standalone module/component for Rock Framework

Installation

From the Command Line:

composer require romeoz/rock-di

In your composer.json:

{
    "require": {
        "romeoz/rock-di": "*"
    }
}

Quick Start

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');

####Constructor injection

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

####Configure properties

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 

Configure properties through setters and getters:

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 

Requirements

  • PHP 5.4+

License

The Rock Dependency Injection is open-sourced software licensed under the MIT license.