PHP code example of dsawardekar / encase-php

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

    

dsawardekar / encase-php example snippets



use Encase\Container;

$container = new Container();
$container->object('logger', new Logger())
          ->factory('worker', 'Worker');


class Worker {

  function needs() {
    return array('logger');
  }

}


$myWorker = $container->lookup('worker');
$myWorker instanceof Worker; // true


$myWorker->logger instanceof Logger; // true


$container->object(...);
$container->factory(...);
$container->singleton(...);


$container->object('key', existingValue);


$container->factory('key', 'FactoryClass');


$container->singleton('key', 'SingletonClass');


class Worker {

  function needs() {
    return array('one', 'two', 'three');
  }

}


class Worker implements INeeds {

  function needs() {
    return array('one', 'two', 'three');
  }

}


// with $callables
$container->object('key', $callable);

// with an anonymous function
$container->object('key', function($container) {
  return 'value';
});


$container->factory('currency', 'Currency');
$container->factory('formatter', 'NumberFormatter');
$container->initializer('currency', array($this, 'initCurrency'));

function initCurrency($currency, $container) {
  $currency->setFormatter($container->lookup('formatter'));
}


class OptionsPackager {

  function onInject($container) {
    $this->container
      ->factory('optionsStore', 'OptionsStore')
      ->factory('optionsValidator', 'OptionsValidator')
      ->factory('optionsPage', 'OptionsPage');
  }

}


$container->packager('optionsPackager', 'OptionsPackager')


$parent = new Container();
$parent->object('logger', new Logger())
  ->factory('worker', 'Worker');

$child = $parent->child();
$child->factory('worker', 'CustomWorker');

$child->lookup('logger'); // from parent container
$child->lookup('worker'); // from child container


class Worker {

  function needs() {
    return array('one', 'two', 'three');
  }

}

worker = container->lookup('worker');
worker->one;
worker->two;
worker->three;
worker->container; // reference to the container object


class Worker implements {

  function needs() {
    return array('logger');
  }

  function onInject($container) {
    $this->logger->log('Worker is ready');
  }

}


function test_it_logs_message_to_the_logger() {
  $mock = $this->getMock('Logger', 'log');
  $mock->expects($this->once())
    ->method('log')
    ->with($this->equalTo('something'));

  $container = new Container();
  $container->factory('worker', 'Worker');
  $container->object('logger', $mock);

  $worker = $container->lookup('worker');
  $worker->start();
}