PHP code example of twinkle / di

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

    

twinkle / di example snippets


$definitions = [
    'hello' => [
        'class' => \HelloWorld::class,
    ]
];
$container = new \Twinkle\DI\Container($definitions);

// 是否注入容器
isset($container['hello'])

// 获取实例
$instance = $container['hello'];
$instance->someMethod();

// 释放
unset($container['hello']);


namespace App\Services;
class HelloService
{

    public function sayHello()
    {
        return 'hello';
    }
}

namespace App\Controllers;
use App\Services\HelloService;
use Twinkle\DI\ServiceLocatorTrait;

/**
 * Class HelloController
 * @package App\Controllers
 * @property HelloService $helloService
 */
class HelloController
{

    use ServiceLocatorTrait;

    public static function supportAutoNamespaces()
    {
        return [
            'App\\Services',
            'Twinkle\\Services'
        ];
    }

    public function indexAction()
    {
        echo $this->helloService->sayHello();
    }

}