在Slim Framework 3中访问类中的应用程序

use*_*740 11 php frameworks slim

当路由处于单独的类而不是index.php时,我无法理解如何访问Slim实例

使用Slim Framework 2时,我总是使用以下内容,但它在Slim 3中不起作用:

$this->app = \Slim\Slim::getInstance();
Run Code Online (Sandbox Code Playgroud)

我试图访问我已在容器中设置的数据库连接,但是来自一个单独的类.这是我目前在index.php中启动Slim应用程序的方法:

require_once("rdb/rdb.php");
$conn = r\connect('localhost');
$container = new \Slim\Container;
$container['rdb'] = function ($c){return $conn;}
$app = new \Slim\App($container);
Run Code Online (Sandbox Code Playgroud)

这是我的路线:

$app->get('/test','\mycontroller:test');
Run Code Online (Sandbox Code Playgroud)

这就是我在mycontroller.php类中得到的,我的路由指向哪个,这显然不起作用,因为$ this-> app不存在:

class mycontroller{
public function test($request,$response){
$this->app->getContainer()->get('rdb');
}
Run Code Online (Sandbox Code Playgroud)

错误消息如下,因为与Slim 2相比,getinstance不属于Slim 3:

Call to undefined method Slim\App::getInstance() 
Run Code Online (Sandbox Code Playgroud)

感谢任何帮助,

关心丹

Mar*_*tin 13

看看Rob Allen创造的Slim 3 Skeleton.

Slim 3大量使用依赖注入,因此您可能也想使用它.

在你的dependencies.php添加内容中:

$container = $app->getContainer();

$container['rdb'] = function ($c) {
    return $conn;
};

$container['Your\Custom\Class'] = function ($c) {
    return new \Your\Custom\Class($c['rdb']);
};
Run Code Online (Sandbox Code Playgroud)

在你的Your\Custom\Class.php:

class Class {
    private $rdb;
    function __construct($rdb) {
        $this->rdb = $rdb;
    }

    public function test($request, $response, $args) {
        $this->rdb->doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您有任何其他问题可以随意提问,我希望这会有所帮助.

更新:

当您像这样定义您的路线时

$app->get('/test', '\mycontroller:test');
Run Code Online (Sandbox Code Playgroud)

Slim \mycontroller:test在你的容器中查找:

$container['\mycontroller'] = function($c) {
    return new \mycontroller($c['rdb']);
}
Run Code Online (Sandbox Code Playgroud)

所以,当你打开www.example.com/test你的浏览器,超薄自动创建的新实例\mycontroller和执行方法test与参数$request,$response$args.并且因为您接受数据库连接作为mycontroller类的构造函数的参数,您也可以在方法中使用它:)


Rob*_*len 6

使用Slim 3 RC2及以后的路线:

$app->get('/test','MyController:test');
Run Code Online (Sandbox Code Playgroud)

CallableResolver会寻找所谓的DIC的关键'MyController',并期望返回控制器,这样你就可以与DIC这样注册:

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您没有注册DIC,那么CallableResolver会将容器传递给您的构造函数,因此您可以创建一个这样的控制器:

class MyController
{
    public function __construct($container) {
        $this->rdb = $container->get('rdb');
    }

    public function test($request,$response){
        // do something with $this->rdb
    }
}
Run Code Online (Sandbox Code Playgroud)