Matt Saunders
Matt Saunders

Reputation: 4371

Symfony2 getters, setters, add and remove

I'm getting really confused by entity properties and what they mean. I understand that get and set allow the application to interact with protected and private properties, but what about add and remove?

When running the command

php app/console doctrine:generate:entities bundle:entity

Sometimes it will generate getters and setters and other times it will generate add and remove properties (and usually a get method as well). I've noticed that it also sometimes depends on the relationship with other entities (i.e. OnetoMany), but not always :-S

Nowhere in the Symfony documentation that I can find is this addressed, and it's causing me to see the message "Neither the property "x" nor one of the methods exist and have public access" way too often. Can anybody provide a succinct explanation of this?

Upvotes: 2

Views: 3035

Answers (2)

Gerry
Gerry

Reputation: 6012

For xxxToMany associations, Doctrine will generate a "adder" and a "remover" instead of a plain setter. The idea is to easily add and/or remove a single object from the collection without needing to pass around the entire collection everytime to the setter.

Note though that these generated methods are an implementation detail you are free to revise. If you prefer a single setter method for example, feel free to implement that one yourself.

I personally don't rely on the accessor generation of Doctrine anymore. Doing it manually allows greater control of your entity's API, and is also quite easy in an IDE like Netbeans or PHPStorm.

Upvotes: 1

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

add and remove are used to deal with collections. If for example your Entity (Let's say A) contains a collection of B elements, then the command will provide an addB() and a removeB() public methods to help you add and remove elements from your collection. It'll also provide a getter which returns the whole collection.

The command generates methods based on the type of attributes you're working with (ArrayCollection, string, ...)

Upvotes: 1

Related Questions