1
resposta

[Dúvida] "id", "area_code" e "number" não estão sendo encontrados no resultado da query que busca os telefones

(Estruturação das pastas) Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Conexao.php v obs: ao executar php conexao.php o var_dump() me retorna o número de linhas afetadas

<?php 

use Alura\Pdo\Infraestructure\Persistence\ConnectionCreator;

require './vendor/autoload.php';

$pdo = ConnectionCreator::createConnection();

var_dump(
    $pdo->exec(statement: 
        "INSERT INTO phones
        (area_code, number, student_id) 
        VALUES 
        ('24', '999999999', 2),
        ('21', '222222222', 3);
    ")
);
// $cre

Phone.php v

<?php

namespace Alura\Pdo\Domain\Model;

class Phone
{
    private ?int $id;
    private string $areaCode;
    private string $number;
    public function __construct(?int $id, string $areaCode, string $number)
    {
        $this->id = $id;
        $this->areaCode = $areaCode;
        $this->number = $number;
    }

    public function formattedPhone(): string{
        return "($this->areaCode) $this->number"; 
    }
} 

?>

PdoStudentsRepository.php v

<?php

namespace Alura\Pdo\Infraestructure\Repository;

use Alura\Pdo\Domain\Model\Student;
use Alura\Pdo\Domain\Model\Phone;
use Alura\Pdo\Domain\Repository\StudentsRepository;
use Alura\Pdo\Infraestructure\Persistence\ConnectionCreator;
use DateTimeImmutable;
use PDO;

class PdoStudentsRepository implements StudentsRepository
{
    private PDO $connection;

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

    public function save(Student $student):bool 
    {
        if($student->id() === null){
            return $this->Insert($student);
        }

        return $this->update($student);
    }

    public function Insert(Student $student): bool{
        $sqlInsert = "INSERT INTO Students (name, birth_date) VALUES (:name, :birth_date);"; 
        $stmt = $this->connection->prepare($sqlInsert);

        if($stmt === false){
            throw new \RuntimeException($this->connection->errorInfo()[2]);
        }

        $sucess = $stmt->execute([
            ':name' => $student->name(),
            ':birth_date' => $student->birthDate()->format('Y-m-d')
        ]);
        
        if($sucess){
            $student->defineId($this->connection->lastInsertId());
        }

        return $sucess;
    }

    public function remove(Student $student):bool
    {
        $sqlDelete = "DELETE FROM Students WHERE id = :id;";
        $stmt = $this->connection->prepare($sqlDelete);
        $stmt->bindValue(':id', $student->id(), PDO::PARAM_INT);

        return $stmt->execute();
    }

    public function update(Student $student): bool{
        $sqlUpdate = 'UPDATE students SET name = :name, birth_date = :birth_date WHERE id = :id;';
        $stmt = $this->connection->prepare($sqlUpdate);
        $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 getBirthAt(\DateTimeInterface $birthDate): array
    {
        $sqlBirth = "SELECT * FROM Students WHERE birth_date = ?;";
        $stmt = $this->connection->prepare($sqlBirth);
        $stmt->bindValue(':birth_date', $birthDate->format('Y-m-d'));
        $stmt->execute();

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

    public function allStudents():array
    {
        $stmt = $this->connection->query('SELECT * FROM Students;');
        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 
    {
        $sqlPhones = "SELECT id, area_code, number FROM phones WHERE student_id = ?";
        $stmt = $this->connection->prepare($sqlPhones);
        $stmt->bindValue(1, $student->id(), PDO::PARAM_INT);
        $stmt->execute();

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

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

v continuar em outro post

1 resposta

Continuação...

Student.php

<?php

namespace Alura\Pdo\Domain\Model;

use Alura\Pdo\Domain\Model\Phone;

class Student
{
    private ?int $id;
    private string $name;
    private \DateTimeInterface $birthDate;
    /**
     * Summary of phones
     * @var array
     */
    private array $phones = [];

    public function __construct(?int $id, string $name, \DateTimeInterface $birthDate)
    {
        $this->id = $id;
        $this->name = $name;
        $this->birthDate = $birthDate;
    }

    public function defineId(int $id){
        if(!is_null($this->id)){
            throw new \DomainException(message:'Você só pode definir o ID uma vez!');
        }

        $this->id = $id;
    }

    public function id(): ?int
    {
        return $this->id;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function changeName($newName){
        $this->name = $newName;
    }

    public function birthDate(): \DateTimeInterface
    {
        return $this->birthDate;
    }

    public function age(): int
    {
        return $this->birthDate
            ->diff(new \DateTimeImmutable())
            ->y;
    }

    public function addPhone(Phone $phone){
        $this->phones[] = $phone;
    }

    /**
     *
     * @return Phone[]
     */
    public function Phones(){
        return $this->phones;
    }
}

lista-alunos.php

<?php

use Alura\Pdo\Domain\Model\Student;
use Alura\Pdo\Infraestructure\Persistence\ConnectionCreator;
use Alura\Pdo\Infraestructure\Repository\PdoStudentsRepository;

require 'vendor/autoload.php';

$pdo = ConnectionCreator::createConnection();
$repository = new PdoStudentsRepository($pdo);
$studentList = $repository->allStudents();

var_dump($studentList);

Quando executo php lista-alunos.php O Erro retornado é este: Insira aqui a descrição dessa imagem para ajudar na acessibilidade