I am just starting a new Silex project. I am using the Cartalyst Sentry Authentication package and I wish to inject into my controller Service Controllers. Here is my attempt at using Silex's built in dependency container which extends Pimple. I would just like some feedback on whether I am going about things the right way and what I can improve.
$app['sentry'] = $app->share(function() use ($app) {
$hasher = new Cartalyst\Sentry\Hashing\NativeHasher;
$userProvider = new Cartalyst\Sentry\Users\Eloquent\Provider($hasher);
$groupProvider = new Cartalyst\Sentry\Groups\Eloquent\Provider;
$throttleProvider = new Cartalyst\Sentry\Throttling\Eloquent\Provider($userProvider);
$session = new Cartalyst\Sentry\Sessions\NativeSession;
$cookie = new Cartalyst\Sentry\Cookies\NativeCookie(array());
$sentry = new Cartalyst\Sentry\Sentry(
$userProvider,
$groupProvider,
$throttleProvider,
$session,
$cookie
);
Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO(
$app['db.dsn'],
$app['db.options']['user'],
$app['db.options']['password']
));
return $sentry;
});
Defining my controller:
// General Service Provder for Controllers
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['user.controller'] = $app->share(function() use ($app) {
return new MyNS\UserController($app);
});
$app->get('/user', "user.controller:indexAction");
Here is my controller, note that app['sentry'] is available to my controller by injecting it into the constructor.
class UserController
{
private $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function indexAction()
{
// just testing various things here....
$user = $this->app['sentry']->getUserProvider()->findById(1);
$sql = "SELECT * FROM genes";
$gene = $this->app['db']->fetchAssoc($sql);
$this->app['monolog']->addDebug(print_r($gene,true));
return new JsonResponse($user);
}
}