One way to manage dependencies when using controller classes is to use an abstract BaseController. This way you can share your common dependencies across all your controllers and only have custom dependencies in their respective controller. You can also create a few types of BaseControllers, one for public API controllers, one for admin controllers, and so on. Here is an example of what I mean, these are just excerpts of what I personally use, some libs may be missing. It’s for example only.
BaseController.php
namespace Controller;
use Core\Alert;
use Core\CSRF;
use Core\JS;
use Core\Input;
use Core\View;
abstract class BaseController
{
protected $alert;
protected $db;
protected $csrf;
protected $js;
protected $input;
protected $view;
public function __construct($container)
{
$this->alert = new Alert;
$this->db = $container->get('db');
$this->csrf = new CSRF;
$this->js = new JS;
$this->input = new Input($container->request);
$this->view = new View($container->response);
$this->view->setTemplatesDirectory($container->get('view.directory') . '/' . $container->get('view.theme'));
}
}
UserController.php
namespace Controller
use Model\User;
class UserController extends BaseController
{
public function get($req, $res, $args)
{
$users = new User($this->db);
$json = $user->getById($args['id']);
$view = [];
$view['content_view'] = ($json === false) ? '{}': $this->view->getSafeJSON($json);
// create new response headers
return $this->view->getJsonResponse($res, 'wrappers/json_view.php', $view);
}
}
If you’re curious $container is used for, its because I use a Config class to manage all my app settings. I then pass the values to Slim’s container. This is how I gain access to them. For example I have a db.php config file that I include.
db.php
// setup db connection
$db = new PDO(
"mysql:host=" . $config->get('db.hostname') . ";dbname=" . $config->get('db.database'),
$config->get('db.username'),
$config->get('db.password')
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['Core\\PDOStatementDebugger', []]);
// store db connection
$config->set('db', $db);
Then in my index.php I return all my config values so slim can use them.
index.php
.
.
.
// instantiate config object
$config = new Config;
.
.
.
// load configs
require_once '../app/config/bootstrap.php';
$app = new App(new Container($config->getConfig()));
require_once '../app/config/routes.php';
.
.
.
.
// init
$app->run();
Hopefully this can help you ease your dependency management.