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]);
}