Access app in class in Slim Framework 3

前端 未结 5 1642
旧时难觅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:49

    With Slim 3 RC2 and onwards given a route of:

    $app->get('/test','MyController:test');
    

    The CallableResolver will look for a key in the DIC called 'MyController' and expect that to return the controller, so you can register with the DIC like this:

    // Register controller with DIC
    $container = $app->getContainer();
    $container['MyController'] = function ($c) {
        return new MyController($c->get('rdb'));   
    }
    
    // Define controller as:
    class MyController
    {
        public function __construct($rdb) {
            $this->rdb = $rdb;
        }
    
        public function test($request,$response){
            // do something with $this->rdb
        }
    }
    

    Alternatively, if you don't register with the DIC, then the CallableResolver will pass the container to your constructor, so you can just create a controller like this:

    class MyController
    {
        public function __construct($container) {
            $this->rdb = $container->get('rdb');
        }
    
        public function test($request,$response){
            // do something with $this->rdb
        }
    }
    

提交回复
热议问题