PHP code example of jakewhiteley / hodl

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

    

jakewhiteley / hodl example snippets


// add
$hodl['Some\Namespace\Foo'] = function(){
    return new Foo();
};

// get
$foo = $hodl['Some\Namespace\Foo'];

// check
if (isset($hodl['Some\Namespace\Foo')) // ...

// remove
unset($hodl['Some\Namespace\Foo']);

$instance = new Foo\Bar();
$instance->prop = 'foobar';

$hodl->addInstance($instance);

// ...

$hodl->get('Foo\Bar')->prop // equals 'foobar'

class Foo
{
	public $var = 'foo';
}

class Bar
{
	public $foo;
	
	public function __construct(Foo $foo)
	{
		$this->foo = $foo;
	}
}

// Add Foo as a singleton
$hodl->addSingleton('Foo', function() {
	return new Foo();
});

$hodl['Foo']->var = 'changed!';


$var = $hodl->resolve('Bar')->foo->var; // equals 'changed!'

$hodl->resolveMethod(Foo::class, 'someMethod');

$foo = new Foo();
$return = $hodl->resolveMethod($foo, 'someMethod', ['amount_of_awesome' => 100]);

class Bar
{
	public $foo;
	
	public function __construct(Foo $foo)
	{
		$this->foo = $foo;
	}
	
	public function methodName(Foo\Baz $baz)
	{
		return $this->foo->var * $baz->var;
	}
}

// Fully resolves methodName and returns an instance of Foo\Baz
$resolvedBaz = $hodl->resolveMethod(
	$hodl->resolve('Bar'),
	'methodName'
);
` php
$hodl->add('Some\Namespace\Foo', function() {
	return new Foo();
});
` php
$foo = $hodl->get('Some\Namespace\Foo');
` php
$hodl['foo'] = function(){
    return new Foo();
};

$hodl->has('foo'); // true

$hodl->remove('foo');

$hodl->has('foo'); // false
` php
$hodl->get('Baz', function($hodl) {
	return new Baz($hodl->get('Some\Namespace\Foo')->someProp);
});
` php
$hodl->addSingleton(Bar::class, function() {
	return new Bar();
});
` php
namespace Foo;

class Foo
{
    function __construct( Bar $bar )
    {
       	$this->bar = $bar;
    }
}
` php
$foo = $hodl->resolve('Foo\Foo');
` php
$hodl->add('Bar', function($hodl) {
	return $hodl->resolve('Bar'); // All of Bar's dependencies will be injected as soon as it is fetched
});

` php
// Basic interface
interface HelloWorld
{
	public function output();
}

// Service
class NeedsResolving
{
	public function __construct(HelloWorld $writer)
	{
		$this->writer = $writer;
	}
	
	public function output()
	{
		$this->writer->output();
	}
}
` php
class MyPrinter implements HelloWorld
{
	public function output()
	{
		echo 'Hello world!';
	}
}

$hodl->bind(MyPrinter::class, HellowWorld::class);

// Correctly gets an instance of MyPrinter
$foo = $hodl->resolve(NeedsResolving::class);

$foo->output(); // Outputs 'Hello world!'