4

Why we generally use getter setters for doctrine2 classes to save and get data?

like below:

<?php
// src/Product.php
class Product
{
    /**
     * @var int
     */
    protected $id;
    /**
     * @var string
     */
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

If we make the the class properties public we can save the data without getter setters. Isn't it?

<?php
// src/Product.php
class Product
{
    /**
     * @var int
     */
    public $id;
    /**
     * @var string
     */
    public $name;
}

3 Answers 3

6
  1. You can't create proxy calls on properties which are required for lazy loaded elements. That is quite heavly used tool by Doctrine.
  2. Getters and setters gives you more flexibility in general than properties.
  3. If overhead of getters and setters is a true issue you should probably consider switching from PHP to some "faster-in-general" platform.
2

because the members of the class (the variables) are generally (and should be) private or protected.

So we use a public set/get method to store and retrieve data from them which otherwise would not be available outside of the class.

Making the class members public could result in them being accidentally overriden, so to prevent this we limit access. Read up on encapsulation.

In the case of doctrine entity classes, it can also be useful to manipulate the incoming/outgoing data, which you can only do with a public method.

heres a good explanation on a different SO forum.

4
2

Rather then public properties or setters, there's more SOLID approach with immutable objects, or value objects, or embeddables when around Doctrine. I recommend you checking those.

Having these, you pass required properties via constructor. In your case:

<?php

class Product
{

    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @param int $id
     * @param string $name
     */
    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

}

And use getters only when needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.