Dice PHP Dependency Injection Container

repository·master·Indexed 19 days ago

https://github.com/level-2/dice

A minimalist, high-performance, single-class Dependency Injection Container for PHP. Dice leverages PHP reflection to automatically resolve dependencies and supports immutable configuration via addRule() and addRules(). It features support for shared instances, method chaining with Dice::CHAIN_CALL, and the injection of superglobals and constants using Dice::GLOBAL and Dice::CONSTANT.

Tokens
1.5K
Snippets
7
Records
8
Agent score
16%

What's inside Dice

  1. Configure Dice using immutability and addRule()

    master

    As of version 4.0, Dice is immutable. Methods that modify the container configuration, such as addRule() and addRules(), do not change the existing instance but instead return a new Dice instance containing the updated rules. You must reassign the result to your variable to persist configuration changes.

    // Correct way to add rules in 4.0+
    $dice = $dice->addRule('PDO', ['shared' => true]);
    
    $db = $dice->create('PDO');
  2. Wrap closures in \Dice\Instance to prevent immediate execution

    master

    To prevent Dice from immediately executing a closure passed as a parameter (such as in constructParams or call), you must wrap the closure in a \Dice\Instance object. This tells Dice to treat the closure as a provider for a value rather than a value to be executed immediately.

    use \Dice\Instance;
    
    $rule->constructParams[] = [
        'instance' => function() {
            return 'abc';
        }
    ];
  3. Install Dice PHP Dependency Injection Container

    master

    Dice is a lightweight, single-file dependency injection container. To use it, simply include the Dice.php file in your project. It requires no further configuration to start working with basic class dependencies.

    <?php
    class A {
    	public $b;
    	public function __construct(B $b) {
    		$this->b = $b;
    	}
    }
    
    class B {}
    
    require_once 'Dice.php';
    $dice = new \Dice\Dice;
    
    $a = $dice->create('A');
    
    var_dump($a->b); // Returns B object
  4. Configure multiple rules with addRules()

    master

    Instead of adding rules one by one, use addRules() to pass an associative array of multiple configurations. This is the preferred method for bulk configuration and is often used in conjunction with json_decode to load rules from an external file.

    $dice->addRules([
    	'\PDO' => [
    		'shared' => true
    	],
    	'Framework\Router' => [
    		'constructParams' => ['Foo', 'Bar']
    	]
    ]);
    
    // Loading from a JSON file
    $dice = $dice->addRules(json_decode(file_get_contents('rules.json')));
  5. Use Dice::create() to instantiate objects

    master

    The primary method for retrieving objects from the container is create(string $className). Dice will automatically resolve dependencies by inspecting the constructor of the requested class via reflection. If no rules are defined, it attempts to instantiate the class with zero configuration.

    $dice = new \Dice\Dice;
    $instance = $dice->create('YourClassName');
  6. Configure object method chaining with Dice::CHAIN_CALL

    master

    Dice supports object method chaining (fluent interfaces) using the call rule combined with the Dice::CHAIN_CALL constant. This allows Dice to construct an object and then immediately call a sequence of methods on it, replacing the initial object with the result of the final call in the chain.

    // Example: Configuring an HTTPRequest with a fluent interface
    $dice = $dice->addRule('HTTPRequest', [
        'call' => [
            ['url', ['http://example.org'], \Dice\Dice::CHAIN_CALL],
            ['method', ['POST'], \Dice\Dice::CHAIN_CALL],
            ['postdata', ['foo=bar'], \Dice\Dice::CHAIN_CALL]
        ]
    ]);
    
    $request = $dice->create('HTTPRequest');
  7. Use Dice::GLOBAL and Dice::CONSTANT in configuration

    master

    When defining rules (especially via JSON), you can inject superglobals and PHP constants into object construction or method calls using special placeholders:

    • Dice::GLOBAL: Used to reference superglobals like $_SERVER, $_GET, etc.
    • Dice::CONSTANT: Used to reference PHP constants (e.g., PDO::ATTR_ERRMODE).
    {
    	"PDO": {
    		"shared": true,
    		"constructParams": [
    			"mysql:dbname=testdb;host=127.0.0.1",
    			"dbuser",
    			"dbpass"
    		],
    		"call": [
    			[
    				"setAttribute",
    				[
    					{"Dice::CONSTANT": "PDO::ATTR_ERRMODE"},
    						{"Dice::CONSTANT": "PDO::ERRMODE_EXCEPTION"}
    				]
    			]
    		]
    	}
    }
  8. Reference Dice configuration keys and constants

    master

    When defining rules, use the following keys and constants:

    Rule Keys

    • shared: Boolean. If true, the instance is shared (singleton behavior).
    • constructParams: Array. Parameters passed to the constructor.
    • call: Array of arrays. Method calls to perform on the instance. Each sub-array follows the format [methodName, [args], [optional: Dice::CHAIN_CALL]].
    • instanceOf: String. The class name this rule is an instance of (used for named instances).
    • inherit: Boolean. If false, the named instance will not inherit rules from the class specified in instanceOf.

    Constants

    • \Dice\Dice::INSTANCE: Used as a key in parameter arrays to signify a named instance (replaces the deprecated 'instance' string).
    • \Dice\Dice::CHAIN_CALL: Used within call rules to enable method chaining.
    • \Dice\Dice::GLOBAL: Placeholder for superglobals in configuration.
    • \Dice\Dice::CONSTANT: Placeholder for PHP constants in configuration.