Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

[Projeto] erro fatal class phone not found

ola! ao tentar exibir a lista de alunos, apos inserir os telefones, recebo um erro dizendo que a classe Phone nao foi encontrada no PdoStudentRepository. segue a mensagem de erro. obrigado!

PHP Fatal error: Uncaught Error: Class "Phone" not found in E:\Curso PHP ALU\BancoDeDados\src\infrastructure\repository\pdoStudentRepository.php:65 Stack trace:

#0 E:\Curso PHP ALU\BancoDeDados\src\infrastructure\repository\pdoStudentRepository.php(50): Alura\Pdo\Infrastructure\Repository\PdoStudentRepository->fillPhonesOf(Object(Alura\Pdo\Domain\Model\Student))

#1 E:\Curso PHP ALU\BancoDeDados\src\infrastructure\repository\pdoStudentRepository.php(25): Alura\Pdo\Infrastructure\Repository\PdoStudentRepository->hydrateStudentList(Object(PDOStatement))

#2 E:\Curso PHP ALU\BancoDeDados\listaAlunos.php(12): Alura\Pdo\Infrastructure\Repository\PdoStudentRepository->allStudents()

#3 {main} thrown in E:\Curso PHP ALU\BancoDeDados\src\infrastructure\repository\pdoStudentRepository.php on line 65

<?php

namespace Alura\Pdo\Infrastructure\Repository;

use Alura\Pdo\Domain\Model\Student;
use Alura\Pdo\Domain\Repository\StudentRepository;

use PDO;
use Phone;

class PdoStudentRepository implements StudentRepository
{
    private PDO $connection;

    public function __construct(PDO $connection)
    {
        $this->connection = $connection;
    }

    public function allStudents(): array
    {
        $sqlQuery = 'SELECT * FROM students;';
        $stmt = $this->connection->query($sqlQuery);

        return $this->hydrateStudentList($stmt);
    }

    public function studentsBirthAt(\DateTimeInterface $birthDate): array
    {
        $sqlQuery = 'SELECT * FROM students WHERE birth_date = ?;';
        $stmt = $this->connection->prepare($sqlQuery);
        $stmt->bindValue(1, $birthDate->format('Y-m-d'));
        $stmt->execute();

        return $this->hydrateStudentList($stmt);
    }
    private function hydrateStudentList(\PDOStatement $stmt): array
    {
        $studentDataList = $stmt->fetchAll();
        $studentList = [];

        foreach ($studentDataList as $studentData) {
            $student = new Student(
                $studentData['id'],
                $studentData['name'],
                new \DateTimeImmutable($studentData['birth_date'])

            );

            $this->fillPhonesOf($student);
            $studentList[] = $student;
        }
            return $studentList;

    }
    public function fillPhonesOf(Student $student): void
    {
       $sqlQuerry = 'SELECT id, area_code, number FROM phones WHERE student_id = ?';
       $stmt = $this->connection->prepare($sqlQuerry);
       $stmt->bindValue(1, $student->id(), PDO::PARAM_INT);
       $stmt->execute();

       $phoneDataList = $stmt->fetchAll();
       foreach ($phoneDataList as $phoneData) {
        $phone = new Phone(
            $phoneData['id'],
            $phoneData['area_code'],
            $phoneData['number']                

        );
        $student->addPhone($phone);
       }
    }

    public function save(Student $student): bool
    {
        if ($student->id() === null) {
            return $this->insert($student);
        }
        return $this->update($student);
    }
    private function insert(Student $student): bool
    {
        $insertQuery = 'INSERT INTO students (name, birth_date) VALUES (:name, :birth_date);';
        $stmt = $this->connection->prepare($insertQuery);
        $success = $stmt->execute([
            ':name' => $student->name(),
            ':birth_date' => $student->birthDate()->format('Y-m-d'),
        ]);
        if ($success) {
            $student->defineId($this->connection->lastInsertId());
        }
        return $success;
    }
    private function update(Student $student): bool
    {
        $updateQuery = 'UPDATE students SET name = :name, birth_date = :birth_date WHERE id = :id;';
        $stmt = $this->connection->prepare($updateQuery);
        $stmt->bindValue(':name', $student->name());
        $stmt->bindValue(':birth_date', $student->birthDate()->format('Y-m-d'));
        $stmt->bindValue(':id', $student->id(), PDO::PARAM_INT);

        return $stmt->execute();
    }

    public function remove(Student $student): bool
    {
        $stmt = $this->connection->prepare('DELETE FROM students WHERE id = ?;');
        $stmt->bindValue(1, $student->id(), PDO::PARAM_INT);
        return $stmt->execute();
    }
}
1 resposta
solução!
<?php

use Alura\Pdo\Infrastructure\Persistence\ConnectionCreator;

require_once 'vendor/autoload.php';

$pdo = ConnectionCreator::createConnection();
echo 'vai';
$pdo->exec("INSERT INTO phones (area_code, number, student_id) VALUES ('24', '999999999', 1),('21', '222222222', 1);");
exit();

$creatTableSql= 'CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, birth_date TEXT);
CREATE TABLE IF NOT EXISTS phones (id INTEGER PRIMARY KEY,area_code TEXT, number TEXT, student_id INTEGER, FOREIGN KEY (student_id) REFERENCES students (id));';
$pdo -> exec($creatTableSql);

só para acrescentar que esse erro passa a acontecer somente após executar o codigo que insere os telefones, se eu der um var dump antes de tentar inserir os telefones, ele mostra tudo de forma normal , inclusive a parte onde estariam ineridos os telefones. obrigado.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software