PhpStorm has a useful feature when quickly creating setters and getters:
Code -> generate -> select the items to generate
This is great for setting basic setters/getters.
However from time to time I want to set more than just setters and getters. For instance I may want to create setters and getters for a one to many or many to many relationship.
i.e.
Many to many
/**
* {@inheritDoc}
*/
public function getOwner()
{
return $this->owner->toArray();
}
/**
* Set the list of user
* @param Collection $owner
*/
public function setOwner( Collection $owner )
{
$this->registeredUsers->clear();
foreach ( $owner as $item ) {
$this->owner[] = $item;
}
}
/**
* Add merchant to the collection
* @param Collection $owner
*/
public function addOwner( Collection $owner )
{
foreach( $owner as $item ) {
$this->owner->add( $item );
}
}
/**
* @param Collection $owner
*/
public function removeOwner( Collection $owner )
{
foreach( $owner as $item ) {
$this->owner->removeElement( $item );
}
}
Is there a way to do this via the same code generation process?
Unfortunately ATM PhpStorm does not support such functionality.
https://youtrack.jetbrains.com/issue/WI-25003 -- watch this ticket (star/vote/comment) to get notified about any progress (so far it's not planned for any specific future version -- possibly because of very low number of votes -- sort of: no votes = no interest = no need to invest resources into it right now).
Related: https://youtrack.jetbrains.com/issue/WI-19891
The only alternative I can think of right now (that would use that Code Generation functionality) .. is to modify template for Getter/Setter so that it contains more than one method (example). This way you can generate setXXX
/addXXX
as well as getXXX
/removeXXX
methods in one go.
Obviously, it would be applied in all cases, so if you need just get/set
then you would need to manually remove add/remove
methods -- that's a drawback of such approach.
Note that File & Code Templates could be IDE-wide (Default
schema) or project-specific (Project
schema) .. so you may use such combined getters/setters in certain projects only.
https://www.jetbrains.com/help/phpstorm/2016.1/file-and-code-templates-2.html
The only other alternative is half manual and requires you to use Live Templates.
With your addXXX
/removeXXX
code sample you may end up with just filling 1 or 2 template variables (just a quick estimation on what I see; the same variable can be used multiple times so will be filled in few places at the same time; entered text can be transformed (limited set of transformations) so it can be re-used in another variable automatically (e.g. you are typing owner
and in another place it is used as Owner
automatically).