RivetIoc
, (*1)
RivetIoc is an auto-wiring (zero configuration) IoC container for PHP to easily manage class dependencies. It features both auto-wiring of dependencies using reflection as well as manual registration for depenency injection., (*2)
Features
- Auto-wiring (zero configuration) dependency injection
- Recursive dependency injection
- Manual registration for more complex dependency management
- Locator trait which exposes commonly used RivetIoc\Ioc methods
Getting Started
Install
$ composer require crishellco/rivet-ioc
System Requirements
PHP >= 5.4.0, (*3)
Documentation
Auto-wiring
Define your classes using type hints, (*4)
namespace App;
class DbDriver
{
...
}
````php
namespace App;
class Db
{
protected $driver;, (*5)
public function __construct(DbDriver $driver)
{
$this->driver = $driver;
}
}, (*6)
````php
namespace App\Services;
class UserService
{
protected $db;
public function __construct(Db $db)
{
$this->db = $db;
}
}
Use RivetIoc to create a new class instance, (*7)
RivetIoc will use constructor type hints to automatically create and inject dependencies, (*8)
$userService = \RivetIoc\Ioc::instance()->make('App\Services\UserService');
// Or use the helper function...
$userService = rivet_make('App\Services\UserService');
Manual dependency registration
Register your dependencies in your application bootstrap, (*9)
\RivetIoc\Ioc::instance()->register('App\Db', function() {
$mysqli = new mysqli('localhost', 'username', 'password', 'mydb');
$db = new App\Db($mysqli);
return $db;
});
Use RivetIoc to create a new class instance, (*10)
RivetIoc will use the registered closure to create and inject dependencies, (*11)
$db = \RivetIoc\Ioc::instance()->make('App\Db');
// Or use the helper function...
$db = rivet_make('App\Db');
Forget a manually registered dependency, (*12)
register_shutdown_function(function() {
\RivetIoc\Ioc::instance()->forget('App\Db');
});
Locator trait
Use the RivetIoc\Traits\Locator trait in a class give access to commonly used RivetIoc\Ioc methods:, (*13)
namespace App\Services;
class UserService
{
use \RivetIoc\Traits\Locator;
protected $dao;
public function __construct()
{
$this->dao = $this->make('App\Doa\UserDao');
// Or use the helper function...
$this->dao = rivet_make('App\Doa\UserDao');
}
}
How to Contribute
Pull Requests
- Fork the RivetIoc repository
- Create a new branch for each feature or improvement
- Send a pull request from each feature branch to the develop branch