Skip to content

Instantly share code, notes, and snippets.

@fideloper
Last active December 10, 2015 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fideloper/4416999 to your computer and use it in GitHub Desktop.
Save fideloper/4416999 to your computer and use it in GitHub Desktop.
A sample application using Containers, for use with explanation of Dependency Injection, Maintainability and Containers - https://gist.github.com/4394248.

Example Application

Here's a portion of a theoretical application.

First, let's set some configurations. Our Application class will extend the container class of choice, Pimple.

We'll use our container to hold our database connection as well as our user object.

Note that we're using the container in order to instantiate our User class with the MySql implementation of a data store. This lets us change the storage in one location (this config file).

/*
Config.php
*/

require_once('path/to/Pimple.php');

$env = 'development';

class Application extends Pimple { /*Probably a bunch of bootstrapping in here*/ }

$app = new Application;

// Set some Containers
$app['config'] = new fancyConfigLoader('path/to/config.ini', $env);

$app['db'] = function() {
	return new MySqlConnection(array(
		'host' => $app['config']['db']['mysql']->host,
		'username' => $app['config']['db']['mysql']->username,
		'password' => $app['config']['db']['mysql']->password,
		'database' => $app['config']['db']['mysql']->database,
	));
}
	
$app['user'] = function() {
	return new User( new MysqlUser( $app['db'] ) );
}

Now that the User object is instantiated in a container, we can call that in our code anywhere. Here's a sample controller.

/*
UserController.php
*/
	
public function show($userId)
{
	$user = $app['user']->getUser($userId);
	
	return new View('user/show', ['user' => $user]);

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment