I want to make the class definition an external file when fetch(PDO::FETCH_CLASS)

Asked 1 years ago, Updated 1 years ago, 92 views

When you create an object with PHP column name properties, you can combine the class definitions and fetch logic to be passed in the same file as follows:

./index.php

<?php
  class message
  {
    public$id;
    public$body;
  }
  $sql = "SELECT id, body FROM message";
  $names=$pdo->query($sql)->fetchAll(PDO::FETCH_CLASS, "Message");

This is the class definition as an external file

./Message.php

<?php
 class message
  {
    public$id;
    public$body;
  }

I wanted to use it by loading it into fetch logic, but I couldn't.

./index.php

<?php
include(."/Message.php");
$sql = "SELECT id, body FROM message";
$stmt = $pdo->query($sql)->fetchAll(PDO::FETCH_CLASS, "Message");

Instance generation is complete, so the class itself can be loaded into the file.

index.php

$m=new Message(1, "hello world");

I did a lot of research, but the main method was to define how to access the ORMapper model class.
Is it better to put fetch logic in the class?
Please tell me how to separate the class definition from fetch.

php database pdo

2022-09-30 11:45

1 Answers

Hello, nice to meet you.

I divided the files with sqlite3 and created a similar environment.
The output shows that the results are mapped to a message.I don't know the full picture of the code from your question, so please compare it.

Below is the code we created.

  • When loading an external class, it is better to use require_once.
  • Attribute is also related to loading, so please check it out

Message.class.php

<?php
class message
{
    public$id;
    public$body;
    public$unknown;
}

test.php

<?php
require_once(__DIR__."/Message.class.php");

$pdo = new\PDO('sqlite::memory:', null, null);

$pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE,\PDO::FETCH_OBJ);

$pdo->prepare("CREATE TABLE IF NOT EXISTS message(`id`INTEGER NULL,`body`text)")->execute();

$pdo->prepare("INSERT INTO message (id, body) VALUES(1,'a')")->execute();
$pdo->prepare("INSERT INTO message (id, body) VALUES(2, 'b')")->execute();
$pdo->prepare("INSERT INTO message (id, body) VALUES(3, 'c')")->execute();

$selectQuery="SELECT id as id, body as body FROM message";

$stm = $pdo->prepare($selectQuery);
$stm->execute(array());

print_r($stm->fetchAll(\PDO::FETCH_CLASS, "Message")); 


2022-09-30 11:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.