PHP code example of wamania / container

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

    

wamania / container example snippets




use Wamania\Container;

class OneService
{
}

$container = new Container();
$oneService = $container->get(OneService::class);



use Wamania\Container;

$container = new Container();
$oneService = $container->has(OneService::class);

class OneService
{
}

class AnotherService
{
    private $oneService;
    
    public function __construct(OneService $oneService)
    {
        $this->oneService = $oneService;
    }
    
    public function getOneService()
    {
        return $this->oneService;
    }
}



use Wamania\Container;

$container = new Container();
$anotherService = $container->get(AnotherService::class);

$oneService = $anotherService->getOneService();



class Db
{
    private $host;
    
    private $user;
    
    private $password;

    // we have defined Container::PARAMETER_PATTERN = '_parameter_%s'
    // if the container find the pattern in an argument, it inject the corresponding parameter value
    public function __construct($_parameter_host, $_parameter_user, $_parameter_password)
    {
        $this->host = $_parameter_host;
        $this->user = $_parameter_user;
        $this->password = $_parameter_password;
    }
}




use Wamania\Container;

$parameters = [
    'host' => 'localhost',
    'user' => 'user',
    'password' => 'secret'
];

$container = new Container($parameters);
$db = $container->get(Db::class);