Andrew Bessa
Andrew Bessa

Reputation: 271

When a PHP object method creates a new object, is it best to save it as an object property?

Lets say I have two classes in PHP, a book class and an author class. Lets say I were to create a new book object.

// $book is now a book class
$book = new book('War and Peace');

Now lets say I want the author from that book. To do so, my object setup requires me to get the author class from the book.

// gets an author class chained with a method to get it's name
$author = $book->getAuthor()->getName();

In the $book->getAuthor() call, would it be best to "save" the author object to a property in book?

public function getAuthor()
{
    if(is_null($this->author_object)) {
        $this->author_object = new author($this->author_name);
    }
    return $this->author_object;
}

The example is probably not the best, but I hope it represents my question well. Also, I know already that database look-ups are a big performance hit, so pretend that is not needed for now.

Basically my question is what is better, creating the author object again if its needed, or saving the author object as a property so it doesn't need to be created again.

Upvotes: 2

Views: 195

Answers (2)

mwhite
mwhite

Reputation: 2111

Yes, it's better to save the Author object as a property of the Book object if you are likely to re-use the author data. However, then you have to worry about things like what happens if you instantiate another Book object that has the same author, and persist changes to that author to the DB using the new Book's object. Then your original Book will have an out-of-date Author object with inconsistent data.

Propel ORM uses a global Instance Pool of related objects to make this process easier. (Although, I'm not sure if it actually maintains consistency in the situation described above, because I seem to recall encountering bugs having to do with that, but it at least prevents database queries to get objects that have already been seen.) In any case, Propel is a nice ORM with exactly the same syntax for related objects and fields as you use, so you might want to consider using it.

Upvotes: 1

prodigitalson
prodigitalson

Reputation: 60413

Generally speaking its pretty hard to imagine a case where it would not be the expectation that that Author is a stored within the Book class and that the Book would not be a member of the Books property on the Author. IT would be fine for them to "lazy load" which is what your example does, but after loaded you would expect to reference the same object with repeated calls, not just the same data.

But there could be instances where that doesnt happen, but then id argue with your choice of naming the method like a basic accessor :-)

Upvotes: 0

Related Questions