Put more information into automatic generated getters and setters in PHPStorm

The default templates for the getter and setter generation are pretty good, but I like them to have a little bit more information and a return $this for the setters. There is a easy way to let PHPStorm do most of the work. To ajust the output of the generation jump to the Code Templates 1 settings.

This is what the default setter template will generate:

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

This is the setter I want to achieve:

/**
 * Set ID
 *
 * @param int $id ID
 *
 * @return $this
 */
public function setId($id)  
{
    $this->_id = $id;

    return $this;
}

Thats the setter config which will do most of the work:

/**
 * Set ${PARAM_NAME}
 *
 * @param ${TYPE_HINT} $${PARAM_NAME} ${NAME}
 *
 * @return $this
 */
public ${STATIC} function set${NAME}($${PARAM_NAME})  
{
#if (${STATIC} == "static")
    self::$${FIELD_NAME} = $${PARAM_NAME};
#else
    $this->${FIELD_NAME} = $${PARAM_NAME};

    return $this;
#end
}

This is what the default getter template will generate:

/**
 * @return int
 */
public function getId()  
{
    return $this->_id;
}

Getter with description (the goal):

/**
 * Get ID
 *
 * @return int
 */
public function getId()  
{
    return $this->_id;
}

Here the getter config which will do most of the work:

/**
 * Get ${FIELD_NAME}
 *
 * @return ${TYPE_HINT}
 */
public ${STATIC} function get${NAME}()  
{
#if (${STATIC} == "static")
    return self::$${FIELD_NAME};
#else
    return $this->${FIELD_NAME};
#end
}

To get a blank line before the return statement you can simple activate the following setting:

Code Style > PHP > Other: "Blank line before return statement"

The only thing left:

  • All fields in camlCase will be still need adjustments as a field lastName will generate a description Get lastName instead of Get last name

I'm still searching for solutions for this. I will post them here if I find them.

  1. Preferences => Editor => File and Code Templates => Code

comments powered by Disqus