r/PHPhelp • • Jun 17 '23

Understanding Array vs Object

Hello everybody,

sorry if it's a dumb question but I need your help.

Between these two solutions for saving a Book after a form submit:

// book_submit.php
$BookMapper = new BookMapper(
    $Database,
    $Log
);
$Book = new Book();
$Book->title = $_POST['title'];
$Book->summary = $_POST['summary'];
$BookMapper->insert($Book);

and

// book_submit.php
$BookMapper = new BookMapper(
    $Database,
    $Log
);
$BookMapper->insert(
    array(
        "title" => $_POST['title'],
        "summary" => $_POST['summary']
    )
);

// Or even
$BookMapper->insert($_POST);

which one is considered the best and why?

The BookMapper class will return a Book object from its select() method, here I'm only talking about saving data.

Thank you

9 Upvotes

13 comments sorted by

6

u/equilni Jun 17 '23

The first is more preferable as the insert method is relying on the Book object with enforced types and defined properties versus an unenforced array.

[
    'title'   => $title, # Is title a string, integer?
    'summary' => $summary, # What is summary here? 
    'author'  => $author # Is this a string of first name/last name, pen name or an object??
]

versus:

class Book { 
    public function __construct(
        public readonly string $title, # PHP 8.1 readonly
        public readonly ?string $summary,
        public readonly Author $author
    ) {
    }
}

class BookMapper {
    public function select(): Book {}
    public function insert(Book $book) {}
    public function update(Book $book){}
    public function delete(Book $book) {}
}

1

u/silentheaven83 Jun 17 '23 edited Jun 17 '23

Thank you. What about multiple related objects?

For eg. I have a book_title table that store multilanguage book titles (bookId, lang, title): (1, "en", Odyssey), (1, "it", "Odissea")

Should I do this or perhaps create a BookService that does it all in a createBook() method?

// book_submit.php  
$BookMapper = new BookMapper(  
    $Database,  
    $Log  
);  
$BookTitleMapper = new BookTitleMapper(  
    $Database,  
    $Log  
);  
$Book = new Book();  
$Book->title = $_POST['title'];  
$Book->summary = $_POST['summary'];  
$Book->id = $BookMapper->insert($Book);

foreach ($_POST['titles'] as $lang => $title) {
    $BookTitle = new BookTitle();
    $BookTitle->bookId = $Book->id;
    $BookTitle->lang = $lang;
    $BookTitle->title = $title;

    $BookTitleMapper->insert($BookTitle);
}

1

u/equilni Jun 18 '23 edited Jun 18 '23

For eg. I have a book_title table that store multilanguage book titles

What the difference then between Book::title and this BootTitle::title? It seems confusing to say the least.

create a BookService that does it all in a createBook() method?

A service would work for this.

1

u/silentheaven83 Jun 18 '23

I'm sorry, I have used the Book "thing" as an example and I forgot the obvious conflict of those two kind of titles.

I meant if I had to store multilanguage titles in an another table instead of just one Book::title.

2

u/whoisthis238 Jun 17 '23

$BookMapper->insert($_POST)

This is massive security hole.

1

u/silentheaven83 Jun 17 '23 edited Jun 17 '23

Could you tell me why?

Even if I would validate data inside the insert method or even if the database class use prepared statement?

2

u/whoisthis238 Jun 17 '23

Prepared statement will do nothing.

And as for validation, if you whitelist only allowed fields then that would mitigate.

The exploit I have in mind is 'mass assignment'. For example Judging by other code you are expecting 'title' and 'summary' fields. But maybe there's 'user_id' field in the table?

Well now you can just modify the HTTP request and pass some arbitrary 'user_id' assigning a book to someone.

Or imagine user table, with a 'role' field. Well now everyone can create user with any role they want. And so on and on...

1

u/silentheaven83 Jun 17 '23

I completely got your point!

Thank you for the explanation.

1

u/whoisthis238 Jun 17 '23

No probs!

1

u/silentheaven83 Jun 17 '23

One last question if I can, should I validate the POST data in the book_submit.php file, or in the insert() method, or in a createBook() method of a BookService class that validates and call the BookMapper->insert() method?

Thank you!

1

u/whoisthis238 Jun 17 '23

Ideally i think you should have a separate Validator service. I don't think you should do it in mapper class. Then again it's kind of subjective, and hard to say without seeing the whole code.

From what I understand you are not using a framework. One of the advantages of using framework is that it will provide a consistent way to validate data.

2

u/[deleted] Jun 17 '23

Normally you would prefer the first method (basically a very basic ORM or object relationship mapping pattern, where you associate a database table and it's relations with an object in PHP). You define your common used database objects (entities) as classes and use instances of them to contain informations. Objects have the big advantage that you can ensure that all required informations are there, you can enforce types and can define additional logic in the form of functions on it. However instead of directly accessing the fields of the class, you would normally encapsulate them via setX and getX functions, so you can control Access to them (check for allowed values and so on).

2

u/cursingcucumber Jun 17 '23

Basically, in this case both of them are good but different. Example one (though often using a constructor or factory) is often used when creating objects programmatically.

Example two is often used when creating objects from request data.

This process is called deserialisation (from e.g. JSON or XML to array) and denormalisation (mapping from an array to an object). Two common libraries for this are the JWS serialiser and the Symfony serialiser. You can find much more about that on their respective websites.

These libraries take care of either using a constructor, public getters and setters or even private properties with reflection.

Side note: in example one you would probably not use properties but use the constructor. Also don't forget the importance of validation!