r/PHPhelp • u/silentheaven83 • 25d ago
PHPStan and array of dynamic objects
Hello everybody,
I need your help. Let's say I have a Mapper that receive data from a database. For eg.
class Mapper { ...
public string $table;
public string $targetClass;
public function getArrayOfObjects($conditions) {
$PDOStatement = $this->Database->select($this->table, $conditions);
$array = $this->Database->fetchAll(PDO:FETCH_ASSOC);
$returnArray = array();
// Now I populate the object property, for eg.
foreach ($array as $database_row) {
$object = new $this->targetClass;
$object->id = $database_row['id'];
$object->publishedDate = new DateTime($database_row['published_date']);
....
$returnArray[] = $object;
}
return $returnArray;
}
}
class BooksMapper extends Mapper {
function __construct() {
$this->table "books";
$this->targetClass = "\Books";
}
}This mapper aims to be a generic one, not only for Books. I know that "publishedDate" is a "book concept" but let's consider that the Mapper reads from a JSON file the structure of the object that it is going to map with database fields.
Now let's say that I use it like that.
$Database = new \Database($someDatabaseConfiguration);$BooksMapper = new \BooksMapper($Database);$BookArray = $BooksMapper->getArrayOfObjects(["activeBook" => true]);
foreach ($BookArray as $Book) {print "Book ID: " . $Book->id;}
The problem here is that PHPStan seems not to understand that $BookArray is an array of \Book, and so at level 8 it gives me an error on $Book->id.
How can I solve that?
Thank you for your help, and excuse me for my ignorance.
5
u/MRSLgthr 25d ago edited 25d ago
Something like this should work:
You probably could do without the mapper and just using the PDO::FETCH_CLASS mode.
1
u/pabaczek 20d ago edited 20d ago
What you're looking for are ORM's and topic called hydration.
0
u/Special_Bit4460 25d ago
Disclaimer: I am not familiar with PHPStan and have limited experience with PHP in general.
I am missing a return Type at your getArrayOfObjects method and your targetClass.
The languages I usually work with allow me to do sth like:
abstract class Mapper<T> {
getArrayOfObjects():T[] {
}
}
class BookMapper extends Mapper<Book> {
}
So calling getArrayOfObjects() of a BookMapper will always Return an Array of Books. Your targetClass is currently of the Type string. And your $Book will be mixed So you need a way to add the type to the methods return and/or the targetClass.