Search code examples
phpdoctrine-ormzend-framework2zend-dbmagic-methods

Zend Framework 2 - Magic Getter and Setter for Doctrine and Annotation forms


I read about a magic getter- and setter function which supersede the huge plie of standard getters and setters. (Link)

I altered the function of Miles because I'm using AnnotationForms and don't want the underscore in the variables like $_name. I updated the magic functions but when trying to call e.g. getName() I get:

Fatal error: Call to undefined method ... Entity::getName()

Here's my code:

<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation as Form;

/**
 * @ORM\Entity
 * @ORM\Table(name="masterdata_entity")
 * @Form\Name("entity")
 * @Form\Attributes({ "class": "form-horizontal" })
 * @Form\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
*/
class Entity
{
  /**
   * @ORM\Id
   * @ORM\Column(type="integer")
   * @ORM\GeneratedValue(strategy="AUTO")
   * @Form\Exclude()
   */
  protected $id;
  /**
   * @ORM\Column(type="string")
   * @Form\Filter({"name":"StringTrim"})
   * @Form\Validator({"name":"StringLength", "options":{"min":1, "max":50}})
   * @Form\Attributes({"type":"text"})
   * @Form\Options({"label":"Name"})
   */
  protected $name;

public function __get($property) {
    return (isset($this->{$property}) ? $this->{$property} : null);
}

public function __set($property, $value) {
    if (isset($this->{$property})) {
        $this->{$property} = $value;
    }
}

public function __isset($property) {
    return isset($this->{$property});
}

}

Any ideas why that is and how I can fix it?


Solution

  • I guess my comment was right. Checking the DoctrineModule\Stdlib\Hydrator\DoctrineObject, you will see that it basically uses the \Zend\Stdlib\Hydrator\ClassMethods. Taking a look at the extract()-function you can see that all ClassMethods will be fetched at line #60

    $methods = get_class_methods($object);
    

    And taking a look at line #63++ you will see that only default getters getX, hasX, isX are to be seen as valid:

    if (!preg_match('/^(get|has|is)[A-Z]\w*/', $method)) {
        continue;
    }
    

    This ultimately means, that you will always have to write your setters and getters. Even though the filesize may become a little bit bigger. It is better for usual IDEs and it is a performance boost, too, even despite filesize.