Access app in class in Slim Framework 3

前端 未结 5 1695
旧时难觅i
旧时难觅i 2021-02-05 23:33

Im having trouble understanding how to access the instance of Slim when a route is in a seperate class than index.php

When using Slim Framework 2 I always used the follo

5条回答
  •  春和景丽
    2021-02-05 23:54

    This was a tough one. @mgansler answer was really helpful, but in his answer he passed a database connection, and not exactly $app inside the controller

    Following the same idea it is possible to send $app though.

    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();
    

提交回复
热议问题