PHPackages                             fanqingxuan/di - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. fanqingxuan/di

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

fanqingxuan/di
==============

v1.2.2(6y ago)120MITPHPPHP &gt;=7.0

Since Dec 21Pushed 5y ago1 watchersCompare

[ Source](https://github.com/fanqingxuan/di)[ Packagist](https://packagist.org/packages/fanqingxuan/di)[ RSS](/packages/fanqingxuan-di/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (7)Used By (0)

**[中文文档地址](README-Zh.md)**

a IOC container for php
-----------------------

[](#a-ioc-container-for-php)

This is a extension which implements Dependency Injection, it's itself a container and it implements the

Inversion of Control pattern.

### enviroment requirement

[](#enviroment-requirement)

**php7.0+**

### Install

[](#install)

```
composer require fanqingxuan/di

```

If you want install it as php extension, please see **[di-ext](https://github.com/fanqingxuan/di-ext)**. The same usage with this package.

### Basic Usage

[](#basic-usage)

```
require_once 'vendor/autoload.php';

use JsonDi\Di;

class Test
{
}

$di = new Di;
//注入的方式
$di->set('test', 'Test');
$di->set("test2", function () {
    return new Test;
});
$di->set("test3", Test::class);
$di->set('test4', new Test);
```

like you can see,there are serveral ways to register services as the follow list.

- string

    ```
    $di->set('test','Test');
    $di->set("test3",Test::class);
    ```
- object instance

    ```
    $di->set('test5',new Test);
    ```
- Closures/Anonymous functions

    ```
    $di->set("test2",function() {
    	return new Test;
    });
    ```

You can pass additonal parameters to closure function.

```
require_once 'vendor/autoload.php';

use JsonDi\Di;
use JsonDi\Config;
$di = new Di;
$di->set('config',new Config(
    [
        'database'  =>  [
            'host'      =>  'localhost',
            'username'  =>  'root',
            'password'  =>  '111111'
        ]
    ]
));
class MysqlDb
{
    public function __construct($config)
    {
        print_r($config);
    }
}
$di->set('db',function () {
    return new MysqlDb($this->get('config')->database);//get the database config from container
});
```

also,you can pass parameter by using the key word of use.

```
$config = [
    'host'      =>  'localhost',
    'username'  =>  'root',
    'password'  =>  '111111'
];
$di->set('db',function () use ($config) {
    return new MysqlDb($config);
});
```

### Advanced Usage

[](#advanced-usage)

- #### Constructor Injection

    [](#constructor-injection)

    This is injection type can pass arguments to the class constructor.

    ```
    class UserService
    {
        protected $userDao;
        protected $userType;

        public function __construct(UserDao $userDao,$userType)
        {
            $this->userDao  = $userDao;
            $this->userType = $userType;
        }
    }
    ```

    We can register the service this way.

    ```
    $di->set(
        'userDao',
        [
    		'className'	=>	UserDao::class
        ]
    );
    $di->set(
    	'userService',
        [
            'className'	=>	UserService::class,
            'arguments'	=>	[
                [
                    'type'	=>	'service',
                    'name'	=>	'userDao',//another service name in the container
                ],
                [
                    'type'	=>	'parameter',
                    'value'	=>	3
                ]
            ]
        ]
    );
    ```
- #### Setter Injection

    [](#setter-injection)

Some class have setters for injection with their specail demand. We modify the above service as the class with setters.

```
class UserService
{
    protected $userDao;
    protected $userType;

    public function setUserDao(UserDao $userDao)
    {
        $this->userDao = $userDao;
    }

    public function setUserType($userType)
    {
        $this->userType = $userType;
    }
}
```

A service with setter injection can be registered as follows:

```
$di->set(
    'userService',
    [
        'className'	=>	'UserService',
        'calls'		=>	[
            [
                'method'	=>	'setUserDao',
                'arguments'	=>	[
                    [
                        'type'	=>	'service',
                    	'name'	=>	'userDao',
                    ]
                ]
            ],
            [
                'method'	=>	'setUserType',
                'arguments'	=>	[
                    [
                        'type'	=>	'parameter',
                    	'value'	=>	3
                    ]
                ]
            ]
        ]
    ]
);
```

- #### Properties Injection

    [](#properties-injection)

You can inject parameters directly into **public attributes** of the class:

```
class UserService
{
    public $userDao;
    public $userType;
    public $tempObj;
}
```

A service with properties injection can be registered as follows

```
$di->set(
	'userService',
    [
        'className'	=>	UserService::class,
        'properties'=>[
            [
                'name'	=>	'userDao',
                'value'	=>	[
                    'type'	=>	'service',
                    'name'	=>	'userDao',//service name in the container
                ]
            ],
            [
                'name'	=>	'userType',
                'value'	=>	[
                    'type'	=>	'parameter',
                    'value'	=>	2,
                ]
            ],
            [
                'name'	=>	'tempObj',
                'value'	=>	[
                    'type'	=>	'instance',
                    'className'	=>	'StdClass',
                    'arguments'	=>	[]
                ]
            ]
        ]
    ]
);
```

### More Advanced Usage

[](#more-advanced-usage)

The next we will give a way that inject service from php file.

```
//service.php
