Error with PDO in PHP SLIM 4

I’m updating a project from slim 3 to slim 4 to be compatible with php 8, but when updating the files where the functions perform searches in the database using PDO, it’s giving this error:

{“message”:“Call to undefined method Doctrine\DBAL\Driver\PDO\Statement::fetchAll()”}

The order is as follows:

router file:

<?php

use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Routing\RouteCollectorProxy;

$app->group('/admin/api', function(RouteCollectorProxy $group) {

    $group->get('/usuarios/[{id}/]', function (Request $request, Response $response) {
        $ApiController = $this->get('ApiController');
        return $ApiController->usersTable($request, $response);
    });

function usersTable

<?php


namespace App\Controllers;

use App\Helpers\Utils;
use App\Helpers\Validator;

use App\Models\Entities\Login;
use App\Models\Entities\Indicator;
use App\Models\Entities\State;
use App\Models\Entities\User;
use App\Models\Entities\IndicadorDia;
use App\Services\DocuSignService;
use App\Services\Email;
use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;

class ApiController extends Controller
{
    public function usersTable(Request $request, Response $response)
    {
        $user = $this->getLogged(true);
        $keys = $values = [];
        //$id = $request->getAttribute('route')->getArgument('id') 
        $id = $args['id']?? null;
        $queryParams = $request->getQueryParams();
        $name = $queryParams['name'] ?? null;
        $type = $queryParams['type'] ?? null;
        $index = $queryParams['index'] ?? null;
        
        if ($name) {
            $keys[] = 'Nome';
            $values[] = $name;
        }
        if ($type > -1) {
            $keys[] = 'Tipo';
            if ($type == 1) {
                $values[] = 'Admin';
            } else {
                $values[] = 'Convencional';
            }
        }
        if (count($keys) > 0) $this->setSearch($user, $keys, $values, 'Usuários');
        $users = $this->em->getRepository(User::class)->list($id, $name, $type, 20, $index * 20);

This code ‘$this->em->getRepository(User::class)->list’ call the file ‘UserRepository.php’

<?php

namespace App\Models\Repository;

use App\Models\Entities\User;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
    public function save(User $entity): User
    {
        $this->getEntityManager()->persist($entity);
        $this->getEntityManager()->flush();
        return $entity;
    }

    public function login(string $email, string $password)
    {
        $user = $this->findOneBy(['email' => $email, 'active' => 1]);
        if (!$user || !password_verify($password, $user->getPassword())) {
            throw new \Exception('Usuário ou senha inválidos.');
        }
        return $user;
    }

    private function generateLimit($limit = null, $offset = null): string
    {
        $limitSql = '';
        if ($limit) {
            $limit = (int)$limit;
            $offset = (int)$offset;
            $limitSql = " LIMIT {$limit} OFFSET {$offset}";
        }
        return $limitSql;
    }

    private function generateWhere(&$params, $id = 0, $name = null, $type = null): string
    {
        $where = '';
        if ($id) {
            $params[':id'] = $id;
            $where .= " AND users.id = :id";
        }
        if ($name) {
            $params[':name'] = "%$name%";
            $where .= " AND users.name LIKE :name";
        }
        if ($type > -1) {
            $params[':type'] = $type;
            $where .= " AND users.type = :type";
        }
        return $where;
    }

    public function list($id = 0, $name = null,  $type = null, $limit = null, $offset = null): array
    {
        $params = [];
        $limitSql = $this->generateLimit($limit, $offset);
        $where = $this->generateWhere($params, $id, $name, $type);
        $pdo = $this->getEntityManager()->getConnection()->getWrappedConnection();
        
        $sql = "SELECT users.id, users.name, users.email, users.type, users.active               
                FROM users
                WHERE 1 = 1 {$where}
                ORDER BY type DESC, name ASC {$limitSql}
               ";
        $sth = $pdo->prepare($sql);
        $sth->execute($params);
        $results = $sth->fetchAll(\PDO::FETCH_ASSOC);
        return $results;
    }

I need PDO to work in the project, since the database was configured with doctrine in the bootstrap.php file

$conn = [
    'dbname' => $configs['settings']['dbname'],
    'user' => $configs['settings']['user'],
    'password' => $configs['settings']['password'],
    'host' => $configs['settings']['host'],
    'driver' => $configs['settings']['driver'],
    'charset' => 'utf8',
];

/**
 * Cria o Entity Manager do doctrine
 */
$entityManager = EntityManager::create($conn, $config);
$conn = $entityManager->getConnection();
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
$config->addCustomDatetimeFunction('DATE', 'App\Helpers\DoctrineDate');

$container->set('em', $entityManager);

This way it worked in slim version 3 and php version 7, what do I need to change for this database search with PDO to work?

You shouldn’t need to change any of the database specific code, so, I suspect something else is going on, such as the database layer not telling you what is really happening.

What does using var_dump($pdo); and using var_dump($sth); show?

Sponsor our Newsletter | Privacy Policy | Terms of Service