1. Go to this page and download the library: Download cee/simple-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/ */
cee / simple-di example snippets
$container = new Cee\SimpleDi\Container();
$classInstance = $container->createServiceOnce('ClassName');
interface Logger {
public function log($message);
}
interface Mailer {
public function send($message, $subject, $to);
}
class NotificationService {
private $mailer;
private $logger;
public function __construct(Mailer $mailer, Logger $logger) {
$this->mailer = mailer;
$this->logger = logger;
}
public function notify($message, array $recipients) {
$subject = 'Notification';
foreach ($recipients as $recipient) {
$this->mailer->send($message, $subject, $recipient);
}
$this->logger->log(...);
}
}
class ErrorLogLogger extends Logger {
public function log($message) {
error_log('Error: ' . $message);
}
}
class SendMailMailer extends Mailer {
public function send($message, $subject, $to) {
mail($to, $subject, $message);
}
}
class NotificationService {
private $mailer;
private $logFileName;
public function __construct(Mailer $mailer, $logFileName) {
$this->mailer = mailer;
$this->logFileName = logFileName;
}
public function notify($message, array $recipients) {
$subject = 'Notification';
foreach ($recipients as $recipient) {
$this->mailer->send($message, $subject, $recipient);
}
file_put_contents($logFileName, ...);
}
}
namespace App;
class Container extends \Cee\SimpleDi\Container {
public function __construct($logFileName) {
$notificationService = new \NotificationService(new SendMailMailer(), $logFileName);
$this->addServiceInstance($notificationService);
}
}
$logFileName = 'log.txt';
$container = new App\Container($logFileName);
$notificationService = $container->createServiceOnce(NotificationService::class);
class NotificationService {
private $mailer;
private $logFileName;
public function __construct(Mailer $mailer, LogFileName $logFileName) {
...
class Repository {
public function __construct(MySqlConnector $mySqlConnector) {
...
}
class Container extends \Cee\SimpleDi\Container {
public function __construct(MySqlConnector $mySqlConnector) {
$this->addServiceInstance($mySqlConnector);
}
}
$mySqlConnector = MySqlConnector::instance();
$container = new App\Container($mySqlConnector);
$repository = $container->createServiceOnce(Repository::class);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.