PHP code example of njasm / container

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

    

njasm / container example snippets


use Njasm\Container\Container;

$container = new Container();

namespace Very\Long\Name\Space;

interface SomeInterface {}

class SomeImplementation implements SomeInterface
{
    // code here
}

$container = new Njasm\Container\Container();
$container->set('Very\Long\Name\Space\SomeInterface', new SomeImplementation());
$container->alias('Some', 'Very\Long\Name\Space\SomeInterface');

$some = $container->get('Some');

$container->set("Username", "John");

echo $container->get("Username");

 $container->bind("MyKey", "\My\Namespace\SomeClass");
 

 $container->bindSingleton("MyKey", "\My\Namespace\SomeClass");
 

namespace \App\Actors;

class Person {
    protected $name;
    protected $age = 24;
    public genre = 'Male';
    
    public function __construct($name = 'John') {
        $this->name = $name;
    }
    
    public function getName() {
        return $this->name;
    }
    
    public function getAge() {
        return $this->age;
    }
    
    public function setAge($age) {
        $this->age = (int) $age;
    }
}

$container->bind(
    "Person",                       // key
    "\App\Actors\Person",           // FQCN
    array("Jane"),                  // constructor dependencies
    array("genre" => "Female"),     // attributes injection
    array("setAge" => array(33))    // call methods
);

// binding with chaining methods 
$container->bind("Person", '\App\Actors\Person')
    ->setConstructorArguments(array("Jane"))        // setConstructorArgument($index, $argument)
    ->setProperty("genre" => "Female")              // setProperties(array("genre" => "Female", ...) also work
    ->callMethod("setAge", array(33));              // callMethods(array('methodName' => 'methodValue', ...));
    
// retrieving the object    
$person = $container->get("Person");
echo $person->getName(); // Jane
echo $person->getAge();  // 33
echo $person->genre      // Female

// calling services and overriding declared dependencies 
$person2 = $container->get(
    "Person", 
    array("Mark"), 
    array("genre" => "Male"), 
    array("setAge" => array(55))
);
echo $person2->getName(); // Mark
echo $person2->getAge();  // 55
echo $person2->genre      // Male

$mailer = new \Namespace\For\My\MailTransport(
    "smtp.example.com", 
    "username", 
    "password", 
    25
); 

$container->set(
    "Mail.Transport", 
    $mailer, 
    array(), // constructor args 
    array(), // public properties injection
    array("withSSL" => array(false)) // calling methods
);

$mailerTransport = $container->get("Mail.Transport");

// calling methods and injecting attributes is also possible
$mailerTransportSsl = $container->get(
    "Mail.Transport", 
    array(), 
    array(), 
    array("withSSL" => array(true))
);

$container->set(
    "Complex",
    function($firstName = "John", $lastName = "Doe") {
        // complex logic here
        // ...
        $theComplexObject = new Complex($firstName, $lastName);
        
        return $theComplexObject;
    }
);

$complex = $container->get("Complex");

// injecting closure dependencies is also possible
$complexJane = $container->get("Complex", array("Jane", "Fonda")); 

$container->set(
    "Mail.Transport",
    function() use (&$container) {
        return new \Namespace\For\My\MailTransport(
            $container->get("Mail.Transport.Config")
        );
    }
);

$container->set(
    "Mail.Transport.Config",
    function() {
        return new \Namespace\For\My\MailTransportConfig(
            "smtp.example.com", 
            "username", 
            "password", 
            25
        );
    }
);

$mailer = $container->get("Mail.Transport");

$container->singleton(
    "Database.Connection",
    function() {
        return new \Namespace\For\My\Database(
            "mysql:host=example.com;port=3306;dbname=your_db", 
            "username", 
            "password"
        );
    }
);

// MyDatabase is instantiated and stored, for future requests to this service, 
// and then returned.
$db = $container->get("Database.Connection");
$db2 = $container->get("Database.Connection");

// $db === $db2 TRUE

$pimple; // is your instantiated pimple container
$pimple["Name"] = $pimple->factory(function() {
   return "John";
}
 
$pimpleAdapter = new \Njasm\Container\Adapter\PimpleAdapter($pimple);
$mainContainer = new \Njasm\Container\Container();
$mainContainer->provider($pimpleAdapter);
 
$mainContainer->has("Name"); // TRUE
echo $mainContainer->get("Name"); // John

namespace My\Name\Space;

class Something
{
    // code
}

// without registering the Something class in the container you can...
$container = new Njasm\Container\Container();
$something = $container->get('My\Name\Space\Something');

//$something instanceof 'My\Name\Space\Something' == true

//once again you can also inject dependencies when calling get method.
$something = $container->get(
    "My\Name\Space\Something", 
    array("constructor value 1", "constructor value 2"),
    array("attributeName" => "value 1"), // attributes
    array("methodName" => array("value 1", "value 2"))
);