duanliang9288 2016-01-16 17:13 采纳率: 100%
浏览 337

如何连接mysql DB Slim 3

I'm new to SLIM3 and can any body guide me how to connect a mysql database and get output a results from a table.

There are many examples for SLiIM v2 and I want to make in in v3

  • 写回答

1条回答 默认 最新

  • doubi9531 2016-01-16 19:43
    关注

    You can use the Container to pass around objects to your Routes. Assuming that you are using closures to handle your routes in Slim, than you could do something like this

    $app = new \Slim\App();
    $container = $app->getContainer();
    
    $container["db"] = new PDO(...); // Replace with your preferred DB Access Method
    
    $app->get("/", function(\Slim\Http\Request $req, \Slim\Http\Response $res, array $args) {
        $connection = $this->get("db"); // Continue your request
    });
    

    A brief explanation of the above code: Generic declaration of the usual objects ($app, $container, etc). The $container object is (by default) Pimple, a Dependency Injection Container which also implements \ArrayAccess. This allows you to treat the object as an array. Using this ability we can set a value into the Container, which will be stored and allow us to access it later. From there, we create a basic route which will be triggered when requesting / and use a closure to respond to the request. The closure has been binded to the Container object by slim, allowing us to access the Containers methods from the $this variable. From there you can treat the object as if you had created it in the function.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料