/** * Load services from PHP file. * * @param string * @return self */ public function load($file) { $items = (array) (include $file); foreach ($items as $id => $service) { $this->container->set($id, $service); } return $this; }
public function load(array $files) { foreach ($files as $file) { $baseKey = $this->namespace . "." . $this->_getBaseKey($file); $this->container->set($baseKey, require_once $file); } return true; }
public function testGetObjectConstructorArguments() { $container = new Container(); $container->set('foo', new \stdClass()); $container->set('foo_bar', new \stdClass()); $builder = new ObjectBuilder($container); $object = $builder->getObject('PSX\\Dependency\\FooService', array('foo'), 'PSX\\Dependency\\FooService'); $this->assertEquals('foo', $object->getProperty()); }
public function register(Container $container) { $db = $container->get("db"); $container->set("UserService", function () use($db) { return new UserService($db); }); $container->set("UserApplicationService", function () use($db) { return new UserApplicationService($db); }); }
protected function getContainer() { $container = new Container(); $container->set('test.param', 'parameterValue'); $container->set('callable', function ($c) { return 'callValue'; }); $container->set('shared', function ($c) { $a = new \stdClass(); $a->mt = microtime(true); return $a; }, true); return $container; }
/** * @expectedException Aura\Di\Exception\ContainerLocked */ public function testLockedSet() { $this->container->lock(); $this->container->set('foo', function () { return new StdClass(); }); }
public function __construct() { $this->model = new \FeatherBB\Model\Install(); $this->available_langs = Lister::getLangs(); Container::set('user', null); View::setStyle('FeatherBB'); }
public function set($key, $value) { $k = $this->findKey($key); if ($k === false) { $k = $key; } return parent::set($k, $value); }
public function testTags() { $container = new Container(); $container->set('container_tags', []); $func = function () { $item = new $this->testClassName(42); return $item; }; $container->set('func', $func, ['name' => 'function', 'param' => 'p42']); /* $functions = $container->getTags('function'); $this->assertEquals(1,count($functions)); $tag = $functions[0]; $this->assertEquals('p42',$tag['param']);*/ }
/** * Constructor * * Instantiate the service locator object. * * @param array $services */ public function __construct(array $services = null) { if (null !== $services) { $this->setServices($services); } if (!Container::has('default')) { Container::set('default', $this); } }
/** * @return array */ public function toArray() { $tmp = new Container(null, []); foreach ($this->changesTracker as $itemKey => $opType) { if ($opType == ITEM_OPERATION_ADD || $opType == ITEM_OPERATION_NEW_VALUE) { $tmp->set($this->get($itemKey)); } } return $tmp->toArray(); }
/** * Set value of specific variable * * @access public * @param string $var Variable name * @param string $value Variable value * @return null * @throws InvalidInstanceException */ public function set($var, $value) { // Get accept class $class = $this->getAcceptClass(); // Check value instance... if (!$value instanceof $class) { throw new InvalidInstanceException('$value', $value, $class); } // if // Set var... return parent::set($var, $value); }
/** * get parameter => service refere * * @covers Phossa\Di\Factory\DereferenceTrait::getReferenceValue */ public function testGetReferenceValue3() { include_once dirname(__DIR__) . '/testData1.php'; // autowiring $aa = $this->object->get('AA'); $this->object->set('cache.test1', '@AA@'); $this->object->set('cache.test2', '%cache.test1%'); $ref1 = new ParameterReference('cache.test2'); // cache.test2 => %cache.test1% => @AA@ $this->assertEquals($aa, $this->invokeMethod('getReferenceValue', [$ref1])); // @BB@ $ref2 = new ServiceReference('BB'); $this->assertTrue($aa->getB() === $this->invokeMethod('getReferenceValue', [$ref2])); }
/** * * Creates a new DI container, adds pre-existing service objects, applies * Config classes to define() services, locks the container, and applies * the Config instances to modify() services. * * @param array $services Pre-existing service objects to set into the * container. * * @param array $config_classes A list of Config classes to instantiate and * invoke for configuring the container. * * @param bool $auto_resolve Enable or disable auto-resolve after the * define() step? * * @return Container * */ public function newInstance(array $services = array(), array $config_classes = array(), $auto_resolve = self::ENABLE_AUTO_RESOLVE) { $di = new Container(new Factory()); $di->setAutoResolve($auto_resolve); foreach ($services as $key => $val) { $di->set($key, $val); } $configs = array(); foreach ($config_classes as $class) { $config = $di->newInstance($class); $config->define($di); $configs[] = $config; } $di->lock(); foreach ($configs as $config) { $config->modify($di); } return $di; }
/** * @covers Phossa\Di\Factory\CallableTrait::resolvePseudoCallable */ public function testResolvePseudoCallable() { // pseudo callable => [ $aa, 'setX'] $call1 = ['@AA@', 'setX']; $res1 = $this->invokeMethod('resolvePseudoCallable', [$call1]); $this->assertTrue($res1[0] === $this->object->get('AA')); $this->assertTrue(is_callable($res1)); // map cache.test => '@AA@' $this->object->set('cache.test', '@AA@'); $call2 = ['%cache.test%', 'setX']; $res2 = $this->invokeMethod('resolvePseudoCallable', [$call2]); $this->assertTrue($res2[0] === $this->object->get('AA')); $this->assertTrue(is_callable($res2)); // real callable $call3 = function () { }; $res3 = $this->invokeMethod('resolvePseudoCallable', [$call3]); $this->assertTrue($res3 === $call3); }
} public function set($name, $val) { $this->dependencies[$name] = $val; } } class Router { protected $request; protected $response; public function __construct(Request $request, Response $response, $path) { $this->request = $request; $this->response = $response; $this->path = $path; // … } } // Create DiC $container = new Container(); // Tell DiC how to create dependencies $container->set('request', function () { return new Request(); }); $container->set('response', function () { return new Response(); }); // Create a router, injecting the dependencies $router = new Router($container->get('request'), $container->get('response'), '/hello'); echo '<pre>'; var_dump($router);
/** * Parse the request * @return self * @api */ public function distribute() { try { Container::get('request')->parse(); } catch (\Exception $e) { $this->error($e->getMessage(), Response::STATUS_BAD_REQUEST); } if (!Container::get('request')->isMethod('get') && !Container::get('request')->isMethod('post') && !Container::get('request')->isMethod('head')) { $this->error(sprintf('Request method "%s" is not allowed!', Container::get('request')->getMethod()), Response::STATUS_METHOD_NOT_ALLOWED); } // analyze request headers foreach (Container::get('request')->getHeaders() as $name => $value) { switch ($name) { case 'Time-Zone': if (in_array($value, timezone_identifiers_list())) { date_default_timezone_set($value); } else { $this->warning(sprintf('The "%s" timezone defined is not valid!', $value)); } break; default: break; } } // user files $type = Container::get('request')->getData('source_type', 'data_input'); $this->setSourceType($type); if ($this->getSourceType() == 'file') { $files = Container::get('request')->getFiles(); if (!empty($files)) { foreach ($files as $name => $path) { $this->addSource(file_get_contents($path), $name); } } } // any test to launch $test = Container::get('request')->getData('test'); if (!empty($test)) { $method = 'testAction_' . $test; if (method_exists($this, $method)) { call_user_func(array($this, $method)); } else { $this->warning(sprintf('Test method "%s" not found!', $test)); } } // end here if no 'source' or 'sources' post data $source = Container::get('request')->getData('source'); $sources = Container::get('request')->getData('sources'); $_sources = $this->getSources(); if (empty($source) && empty($sources) && empty($_sources)) { $this->warning('No source to parse!')->serve(); } else { if (!empty($sources)) { $this->setSources(array_merge($_sources, $sources)); } if (!empty($source)) { $this->addSource($source); } } // debug mode on? $this->setDebug(Container::get('request')->getData('debug', false)); // load the MDE parser if (!class_exists('\\MarkdownExtended\\MarkdownExtended')) { $this->error('Class "\\MarkdownExtended\\MarkdownExtended" not found!'); } Container::set('mde_parser', new \MarkdownExtended\MarkdownExtended()); return $this; }
/** * get the error info encapsulated in a container * @return Container * @access public */ public function getError() { $container = $this->getObserver()->get('error'); if (!$container instanceof Container) { $container = new Container(); $data = $this->getObserver()->get('error'); if (is_array($data)) { foreach ($data as $k => $v) { $container->set($k, $v); } } $this->getObserver()->set('error', $container); } return $container; }
public function testClosureThisMustBeContainer() { $di = new Container(); $di->set('test', function () { return $this; }); $this->assertSame($di, $di->get('test')); }
public function __invoke($req, $res, $next) { $authCookie = Container::get('cookie')->get(ForumSettings::get('cookie_name')); if ($jwt = $this->get_cookie_data($authCookie)) { $user = AuthModel::load_user($jwt->data->userId); $expires = $jwt->exp > Container::get('now') + ForumSettings::get('o_timeout_visit') ? Container::get('now') + 1209600 : Container::get('now') + ForumSettings::get('o_timeout_visit'); $user->is_guest = false; $user->is_admmod = $user->g_id == ForumEnv::get('FEATHER_ADMIN') || $user->g_moderator == '1'; if (!$user->disp_topics) { $user->disp_topics = ForumSettings::get('o_disp_topics_default'); } if (!$user->disp_posts) { $user->disp_posts = ForumSettings::get('o_disp_posts_default'); } if (!file_exists(ForumEnv::get('FEATHER_ROOT') . 'featherbb/lang/' . $user->language)) { $user->language = ForumSettings::get('o_default_lang'); } if (!file_exists(ForumEnv::get('FEATHER_ROOT') . 'style/themes/' . $user->style . '/style.css')) { $user->style = ForumSettings::get('o_default_style'); } // Refresh cookie to avoid re-logging between idle $jwt = AuthModel::generate_jwt($user, $expires); AuthModel::feather_setcookie('Bearer ' . $jwt, $expires); // Add user to DIC Container::set('user', $user); $this->update_online(); } else { $user = AuthModel::load_user(1); $user->disp_topics = ForumSettings::get('o_disp_topics_default'); $user->disp_posts = ForumSettings::get('o_disp_posts_default'); $user->timezone = ForumSettings::get('o_default_timezone'); $user->dst = ForumSettings::get('o_default_dst'); $user->language = ForumSettings::get('o_default_lang'); $user->style = ForumSettings::get('o_default_style'); $user->is_guest = true; $user->is_admmod = false; // Update online list if (!$user->logged) { $user->logged = time(); // With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table switch (ForumSettings::get('db_type')) { case 'mysql': case 'mysqli': case 'mysql_innodb': case 'mysqli_innodb': case 'sqlite': case 'sqlite3': DB::for_table('online')->raw_execute('REPLACE INTO ' . ForumSettings::get('db_prefix') . 'online (user_id, ident, logged) VALUES(1, :ident, :logged)', array(':ident' => Utils::getIp(), ':logged' => $user->logged)); break; default: DB::for_table('online')->raw_execute('INSERT INTO ' . ForumSettings::get('db_prefix') . 'online (user_id, ident, logged) SELECT 1, :ident, :logged WHERE NOT EXISTS (SELECT 1 FROM ' . ForumSettings::get('db_prefix') . 'online WHERE ident=:ident)', array(':ident' => Utils::getIp(), ':logged' => $user->logged)); break; } } else { DB::for_table('online')->where('ident', Utils::getIp())->update_many('logged', time()); } // $jwt = AuthModel::generate_jwt($user, Container::get('now') + 31536000); // AuthModel::feather_setcookie('Bearer '.$jwt, Container::get('now') + 31536000); // Add $user as guest to DIC Container::set('user', $user); } translate('common'); // Load bans from cache if (!Container::get('cache')->isCached('bans')) { Container::get('cache')->store('bans', Cache::get_bans()); } // Add bans to the container Container::set('bans', Container::get('cache')->retrieve('bans')); // Check if current user is banned $this->check_bans(); // Update online list $this->update_users_online(); return $next($req, $res); }
// $p = new Person(); // var_dump($p->name, $p->age); class Container { private $data = array(); public function get($key) { return array_key_exists($key, $this->data) ? $this->data[$key] : null; } public function set($key, $value) { $this->data[$key] = $value; } } $c = new Container(); $c->set('name', 'foo'); $c->set('age', 20); class parentClass { protected $container; function __construct($c) { $this->container = $c; } function __get($key) { return $this->container->get($key); } } class subClass extends parentClass {
<div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default my-panel"> <div class="panel-heading"> OUTPUT </div> <div class="panel-body"> <?php //$db->connect(); $container = new Container(); echo '<div class="subtitle">1. part</div>'; // sets providers $container->set("book", "Lord of the flies"); // provider as a scalar $container->set("number", 317); // provider as a scalar $container->set("now", function () { return date("F j, Y, g:i a"); // provider as a closure }); $container->set("hello", function ($firstName, $lastName) { return "Hello {$firstName} {$lastName}"; // provider as a closure }); $container->set("numbers", array(5, 10, 50, 100)); // provider as an array $container->set("colors", array('red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF')); // provider as an associative array
/** * @covers ::replaceData */ public function testReplaceData() { $this->container->set('some', 'data'); $this->container->replaceData(['some_other' => 'data']); $this->assertEquals(['some_other' => 'data'], $this->container->getData()); }
<?php namespace App; // DIC configuration // view renderer Container::set('view', function ($c) { return new \App\Core\View(); }); // hooks Container::set('hooks', function ($c) { return new \App\Core\Hooks(); }); // flash messages Container::set('flash', function ($c) { return new \Slim\Flash\Messages(); }); // cookies Container::set('cookie', function ($c) { $request = $c->get('request'); return new \Slim\Http\Cookies($request->getCookieParams()); });
/** * Data function returns a container object, where all internal * data is stored. * @return Container * @access private */ private function data() { static $data; if (isset($data)) { return $data; } $data = new Container(); $params = array("cache" => SC::get('board_config.always_cache_bust') ? SC::get('board_config.time_now') . '_' . mt_rand(1, 999999) : SC::get('board_config.cache_bust'), 'yui_version' => '2.6.0'); $data->set("settings", $params); // Until all content is in grids, we need this var // REMOVE ONCE EVERY SINGLE PAGE ON THE SITE IS IN GRIDS $data->set('enable_nongrid', TRUE); if (isset($_GET['login_success']) && SC::get('userdata.user_id') < 1 && empty($_COOKIE)) { SC::set('board_config.sys_message', 'Gaia Online requires browser cookies. Please enable cookies in your browser and try again. Mmmm cookies.'); } $data->set('ext_script_js', array()); $data->set('script_js', array()); $data->set('script_css', array()); $data->set('script_css_ie', array()); return $data; }
/** * @param Container $container * @depends testMakeContainer */ public function testSet(Container $container) { $this->assertEquals('H', $container->set('h', 'H')); $this->assertTrue($container->has('h')); }
public function __invoke($req, $res, $next) { // Set headers $res = $this->set_headers($res); // Block prefetch requests if (isset($this->app->environment['HTTP_X_MOZ']) && $this->app->environment['HTTP_X_MOZ'] == 'prefetch') { return $this->app->response->setStatus(403); // Send forbidden header } // Populate Slim object with forum_env vars Container::set('forum_env', $this->forum_env); // Load FeatherBB utils class Container::set('utils', function ($container) { return new Utils(); }); // Record start time Container::set('start', Utils::get_microtime()); // Define now var Container::set('now', function () { return time(); }); // Load FeatherBB cache Container::set('cache', function ($container) { $path = $this->forum_env['FORUM_CACHE_DIR']; return new \FeatherBB\Core\Cache(array('name' => 'feather', 'path' => $path, 'extension' => '.cache')); }); // Load FeatherBB permissions Container::set('perms', function ($container) { return new \FeatherBB\Core\Permissions(); }); // Load FeatherBB preferences Container::set('prefs', function ($container) { return new \FeatherBB\Core\Preferences(); }); // Load FeatherBB view Container::set('template', function ($container) { return new View(); }); // Load FeatherBB url class Container::set('url', function ($container) { return new Url(); }); // Load FeatherBB hooks Container::set('hooks', function ($container) { return new Hooks(); }); // Load FeatherBB email class Container::set('email', function ($container) { return new Email(); }); Container::set('parser', function ($container) { return new Parser(); }); // Set cookies Container::set('cookie', function ($container) { $request = $container->get('request'); return new \Slim\Http\Cookies($request->getCookieParams()); }); Container::set('flash', function ($c) { return new \Slim\Flash\Messages(); }); // This is the very first hook fired Container::get('hooks')->fire('core.start'); if (!is_file(ForumEnv::get('FORUM_CONFIG_FILE'))) { // Reset cache Container::get('cache')->flush(); $installer = new \FeatherBB\Controller\Install(); return $installer->run(); } // Load config from disk include ForumEnv::get('FORUM_CONFIG_FILE'); if (isset($featherbb_config) && is_array($featherbb_config)) { $this->forum_settings = array_merge(self::load_default_forum_settings(), $featherbb_config); } else { $this->app->response->setStatus(500); // Send forbidden header return $this->app->response->setBody('Wrong config file format'); } // Init DB and configure Slim self::init_db($this->forum_settings, ForumEnv::get('FEATHER_SHOW_INFO')); Config::set('displayErrorDetails', ForumEnv::get('FEATHER_DEBUG')); if (!Container::get('cache')->isCached('config')) { Container::get('cache')->store('config', \FeatherBB\Model\Cache::get_config()); } // Finalize forum_settings array $this->forum_settings = array_merge(Container::get('cache')->retrieve('config'), $this->forum_settings); Container::set('forum_settings', $this->forum_settings); // Set default style and assets Container::get('template')->setStyle(ForumSettings::get('o_default_style')); Container::get('template')->addAsset('js', 'style/themes/FeatherBB/phone.min.js'); // Run activated plugins self::loadPlugins(); // Define time formats and add them to the container Container::set('forum_time_formats', array(ForumSettings::get('o_time_format'), 'H:i:s', 'H:i', 'g:i:s a', 'g:i a')); Container::set('forum_date_formats', array(ForumSettings::get('o_date_format'), 'Y-m-d', 'Y-d-m', 'd-m-Y', 'm-d-Y', 'M j Y', 'jS M Y')); // Call FeatherBBAuth middleware return $next($req, $res); }
/** * Sets a service. * * @param string $id The service identifier * @param object $service The service instance */ public function set($id, $service) { unset($this->definitions[$id]); unset($this->aliases[$id]); parent::set($id, $service); }
/** * @param string $key * @param mixed $value * * @return CollectionInterface */ protected function setParameter($key, $value) { return parent::set($key, $value); }
$testdelete->set('bla', 'woeiwoei'); assert('$testdelete->is_set("bla")'); $testdelete->delete('bla'); assert('!$testdelete->is_set("bla")'); /* Test underscores and dashes juggling */ $c = new Container(); $c->set('foo_bar', 'baz'); assert('$c->get("foo-bar") === "baz"'); assert('$c->get("foo_bar") === "baz"'); $c->set('foo-bar', 'baz2'); assert('$c->get("foo-bar") === "baz2"'); assert('$c->get("foo_bar") === "baz2"'); $c->add('some-list', 'value'); $c->add('some_list', 'value'); assert('count($c->get("some-list")) === 2'); /* Test getdefault() and setdefault() */ $c = new Container(); assert('$c->getdefault("foo", "defaultvalue") === "defaultvalue"'); $c->set('foo', 'anothervalue'); assert('$c->getdefault("foo", "defaultvalue") === "anothervalue"'); assert('$c->is_set("bar") === false'); $c->setdefault('bar', 'somevalue'); assert('$c->get("bar") === "somevalue"'); $c->set('bar', 'anothervalue'); assert('$c->get("bar") === "anothervalue"'); $c->setdefault('bar', 'somevalue'); /* should do nothing */ assert('$c->get("bar") === "anothervalue"'); $c->_set('foo', 'bar123'); assert('$c->_getdefault("bar") === "anothervalue"'); assert('$c->_getdefault("this-one-is-not-set", "the-answer") === "the-answer"');