0

如何获得在dependicies.php 中创建的模型类中的PDO 连接?

我有控制器和模型类。

我的路线:

$app->group('/users', function (Group $group) {
  $group->get('', [UsersController::class, 'getAll'], function (Request $request, Response $response) {
     return $response;
  });
});

我的控制器:

namespace App\Application\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Application\Models\UsersService;

class UsersController
{

  private $_usersSvc;

  public function __construct()
  {
    $this->_usersSvc = new UsersService();
  }

  public function getAll(Request $request, Response $response)
  {
    $uri = $request->getUri();
    parse_str($uri->getQuery(), $params);
    $result = $this->_usersSvc->getAll($params);
    $response->getBody()->write(json_encode($result));

    return $response;
  }

我在 dependencies.php 中的 DI 设置

return function (ContainerBuilder $containerBuilder) {
    $containerBuilder->addDefinitions([
        LoggerInterface::class => function (ContainerInterface $c) {
            $settings = $c->get(SettingsInterface::class);

            $loggerSettings = $settings->get('logger');
            $logger = new Logger($loggerSettings['name']);

            $processor = new UidProcessor();
            $logger->pushProcessor($processor);

            $handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
            $logger->pushHandler($handler);

            return $logger;
        },
        PDO::class => function (ContainerInterface $c) {
            $settings = $c->get('settings');
            $db = [
              'dbname' => $settings['db']['name'],
              'user'   => $settings['db']['username'],
              'pass'   => $settings['db']['password'],
              'host'   => $settings['db']['host']
            ];
      
            $connection = new PDO("mysql:host=" . $db['host'] . ";port=3306;dbname=" . $db['dbname'], $db['user'], $db['pass']);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
      
            return $connection;
          },        
    ]);
};

我的模特班

namespace App\Application\Models;

use App\Application\Models\DataObjects;
use Psr\Log\LoggerInterface;
use Psr\Container\ContainerInterface;
use DateTime;
use PDO;

class UsersService extends DataObjects
{
    protected $db;

    public function __construct()
    {   

    }

    public function getAll($params)
    {
        $orderBy = (isset($params['sortdesc']) && empty($params['sortdesc']) === false) ? $params['sortdesc'] . ' DESC' : null;
        if ($orderBy === null) {
            $orderBy = (isset($params['sortasc']) && empty($params['sortasc']) === false) ? $params['sortasc'] . ' ASC' : '';
        }

        return $this->loadAll($orderBy);
    }
}

如何从模型类中的 dependencies.php 访问 $connection 实例?

4

0 回答 0