Max Bündchen
Max Bündchen

Reputation: 1362

Access $app object from controller

How to get access to $app inside a controller as the Slim 3.3 injects only the ContainerInterface?

Code to illustrate the question:

$app = new \Slim\App;

$app->get('/home', 'HomeController:get');

$app->run();

class HomeController {
    private $ci;

    public function _construct($ci) {
        $this->ci = $ci;
    }

    public function get($request, $response) {
        $this->ci->get(...);
        // How to access $app and dependencies like $app->jwt?
    }
}

Upvotes: 3

Views: 1637

Answers (2)

Leo Leao
Leo Leao

Reputation: 161

This was a tough one.

Slim 3 heavily uses dependency injection, so you might want to use it too.

First inside your dependencies.php you need to grab the $app and throw it in a container to inject it to the Controller later.

$container['slim'] = function ($c) {
   global $app;
   return $app;
};

Then you got to inject it:

// Generic Controller
$container['App\Controllers\_Controller'] = function ($c) {
    return new _Controller($c->get('slim'));
};

Now on your controller.php:

private $slim;

/**
     * @param \Psr\Log\LoggerInterface       $logger
     * @param \App\DataAccess                $dataaccess
     * @param \App\$app                      $slim
     */
    public function __construct(LoggerInterface $logger, _DataAccess $dataaccess, $slim)
    {       
        $this->logger = $logger;
        $this->dataaccess = $dataaccess;
        $this->slim = $slim;
    }

Now you just got call it like this:

$this->slim->doSomething();

Upvotes: 1

brense
brense

Reputation: 412

You can make your own 'singleton' to mimic Slim::getInstance(); ;)

class Anorexic extends \Slim\App {
    private static $_instance;
    public static function getInstance(){
        if(empty(self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

Then change your initialization like this:

// $app = new \Slim\App;
$app = Anorexic::getInstance();

Now you can get your \Slim\App instance anywhere in your code by calling Anorexic::getInstance(); Ofcourse you should never try this at home :P

Upvotes: 0

Related Questions