Search code examples
phpumlgetter-setterenterprise-architectmagic-methods

Magic getters and setters in Enterprise Architect


I'm using Enterprise Architect to make a UML class diagram and generate PHP5 code with it. Using this, one can make getters and setters for an attribute, which looks like this in the code (only relevant lines shown):

private $id;

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

/**
 * 
 * @param newVal
 */
public function setId($newVal)
{
    $this->id = $newVal;
}

I'd like to use the magic methods __get($property) and __set($property, $value) instead of seperate methods for each property. Is it possible, and if so, how?

It could look like this, for the getter:

public function __get($property)
{
    switch ($property) {
        case 'id': return $this->id; break;
        default: return null;
    }
}

Solution

  • I agree with other people on this page that it's bad practise and you should stick to plain old getters and setters over the magic methods. Once you need validation or other computations in the accessors/mutators your switch/case will explode. It's a mess to maintain and not exactly inheritance friendly. A child class with the magic methods is technically overwriting the parent's magic method.

    However, you can do that by modifing the Code Templates with the Code Template Editor of EA.

    Quoting from Enterprise Architect User Guide on Code Templates:

    Code templates enable you to customize code generation of existing languages. For example:

    • Modify the file headers created when generating new files
    • Change the style of the generated code (such as indenting or brace position) to match the required coding standards
    • Handle particular stereotypes to generate things like specialized method bodies and extra methods.

    and further:

    Enterprise Architect's base code templates specify the transformation from UML elements to the various parts of a given programming language. The templates are written as plain text with a syntax that shares some aspects of both mark-up languages and scripting languages.

    Here is a sample picture of the Code Editor with some template loaded into it:

    Enterprise Architect Code Template Editor

    I am not familiar with the Editor nor the template language they use, so I cannot provide you with a working example. But I guess you can figure it out from there if you really want to modify the template.