PHP code example of g4 / di

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

    

g4 / di example snippets



namespace MyNamespace;

use G4\DI\Container;

class DI extends Container
{
    /**
     * @return \MyNamespace\MyConfig
     */
    public static function configInstance()
    {
        return self::registerShare(function (DI $c) {
            return new \MyNamespace\MyConfig();
        });
    }
    
    /**
     * @return \MyNamespace\MyClass
     */
    public static function myClassInstance()
    {
        return self::registerFactory(function (DI $c) {
            return new \MyNamespace\MyClass($c::configInstance());
        });
    }
}


use MyNamespace\DI;

$myClass = DI::myClassInstance();

// the above call is equivalent to:
// $myConfig = new \MyNamespace\MyConfig();
// $myClass = new \MyNamespace\MyClass($myConfig);