PHP code example of maplephp / container

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

    

maplephp / container example snippets


use MaplePHP\Container\Container;

$container = new Container();

// You can set mixed values in the container
$container->set("hasEmail", true);

$hasEmail = $container->get("hasEmail")->get();
var_dump($hasEmail); // Result in: (bool) true

$container->factory("factoryKey", function() {
    $a = new TestClassA();
    $b = new TestClassB();
    return new TestClassC($a, $b);
});
echo $container->get("factoryKey"); // Will return TestClassC


use MaplePHP\Container\Container;
use MaplePHP\Container\Autowire;
use App\Services\MailService;

$container = new Container();
$container->set("MailService", new Autowire(MailService::class));

// This will return "MailService" with all dependencies resolved on constructor
$mailService = $container->get("MailService")->get();
echo $mailService->send();

use MaplePHP\Container\EventHandler;

$logger = new EventHandler();
$logger->addHandler(new Logger());
$logger->addEvent(function() {
    var_dump("Executed in conjunction with logger every method");
    // You could add a mail function that will send log message to you,
});
echo $logger->error("A error message to log");
// Will log message AND execute the event

$logger = new EventHandler();
$logger->addHandler(new Logger(), ["emergency", "alert", "critical"]);
$logger->addEvent(function() {
    var_dump("Executed in conjunction with logger event method");
    // You could add a mail function that will send log message to you,
});
echo $logger->error("A error message to log");
// Will only log message
echo $logger->alert("A error message to log");
// Will log message AND execute the event

use MaplePHP\Container\Interfaces\EventInterface;

$callableFunction = new class implements EventInterface {

    public function someMethod(string $what): string
    {
        return "Hello {$what}!";
    }

    // Resolve method will be executed in conjunction 
    // with logger event method
    public function resolve(): void
    {
        var_dump($this->someMethod("world"));
    }
};

$logger = new EventHandler();
$logger->addHandler(new Logger(), ["emergency", "alert", "critical"]);
$logger->addEvent(function() {
    var_dump("Executed in conjunction with logger event method");
    // You could add a mail function that will send log message to you,
});
echo $logger->error("A error message to log");
// Will only log message
echo $logger->alert("A error message to log");
// Will log message AND execute the event