Skip to content

Instantly share code, notes, and snippets.

@pjdietz
Last active August 29, 2015 14:18
Show Gist options
  • Save pjdietz/77f67ff5af769fe843eb to your computer and use it in GitHub Desktop.
Save pjdietz/77f67ff5af769fe843eb to your computer and use it in GitHub Desktop.
DI Container with configuration
<?php
namespace MyNamespace;
/**
* Dependency injection container
*/
class Container extends \Pimple\Container
{
/**
* Create a new container
*
* @param array $configuration Optional configuration to add to the Container.
*/
public function __construct($configuration = null)
{
parent::__construct();
// Path to a default configuration file.
$this["CONFIGURATION_FILE"] = realpath(__DIR__ . "/../../../conf/config.php");
// Apply an array to this container.
$this["applyConfiguration"] = function ($c) {
return function ($configuration) use ($c) {
if ($configuration) {
foreach ($configuration as $key => $value) {
unset($c[$key]);
$c[$key] = $value;
};
}
};
};
// Include a file that returns an array and apply it to this contianer.
$this["applyConfigurationFile"] = function ($c) {
return function ($path) use ($c) {
if (file_exists($path)) {
$configuration = include $path;
$c["applyConfiguration"]($configuration);
}
};
};
// Add the main stuff for your Container here.
// At the end, call the
///////////////////
// Configuration //
///////////////////
// Add optional configuration passed to the constructor.
$this["applyConfiguration"]($configuration);
// Add the optional configuration file after the main keys have been added.
$this["applyConfigurationFile"]($this["CONFIGURATION_FILE"]);
}
}
#!/usr/bin/env php
<?php
use MyNamespace\Container;
require_once __DIR__ . "/../vendor/autoload.php";
$container = new Container();
$keys = $container->keys();
sort($keys);
foreach ($keys as $key) {
$value = $container[$key];
// NOTE: If you want to see strings wrapped in ", move the is_string check to the second part.
if (is_numeric($value) || is_string($value)) {
print "$key: $value\n";
} elseif (is_bool($value) || is_array($value) || $value instanceof \stdClass) {
print "$key: " . json_encode($value, JSON_PRETTY_PRINT) . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment