January 16, 2013

Sublime Text 2 snippet Getter/Setter

It's almost a month since I embraced Sublime Text as my daily editor, even for coding. And I love how much easier my life is now. As an example, here's a snippet I just made to avoid writing all that getter/setter bolierplate over and over again in PHP…

<snippet>
    <content><![CDATA[
private \$${1:memberName};

public function get${1/(?:^|_)(.)/\u$1/g}()
{
 return \$this->$1;
}

public function set${1/(?:^|_)(.)/\u$1/g}(\$${2:value})
{
 \$this->$1 = \$$2;
 return \$this;
}
]]></content>
    <tabtrigger>gsetter</tabtrigger>
    <scope>source.php</scope>
</snippet>

The odd ${1/(?:^|_)(.)/\u$1/g} converts into CamelCase what you typed at memberName, uppering the first char and all that are preceded by underscore, removing the latter. So applicationName and member_name both become ApplicationName.

Just go to Tools > New Snippet, paste the code, save, and you're ready to go. Type gsetter in a PHP file, press Tab and that's all. Easy as pie.