Defining file templates

I want to create a new class file template like this:

Class name: TheClassName

File name:

Is that possible? If not possible through templates, is it possible trough writing a simple plugin.


Also I copied "PHP class" template into new one including the "#if (${NAMESPACE})" part. When I create file through normal php template without entering namespace, I don't get namespace declaration. However when I use the template I created and I leave the namespace blank, the #if (${NAMESPACE}) writes empty namespace like this:

namespace ;

Why the #if statement doesn't work. I'm using PHPStorm PS-145.256.26 (updated from EAP install)

1 comment
Comment actions Permalink

Hi there,

> Is that possible?

Yes -- you can alter class name based on file name using Apache Velocity templating language (that is used if File & Code Templates)

${NAME} is a variable that holds file name (excluding extension). In your case it will be "" (in case if you did not put it as part of extension for that template) -- you would need to get rid of ".inc" part yourself.

Here is some example (can be done better though)

## will convert foo_BAR_meow into FooBarMeow

#set($class = ${NAME})
#set($parts = $class.split("_"))
#set($final = "")
#set($current = "")
#foreach($current in $parts)
    #set($fc = $current.substring(0,1).toUpperCase())
    #set($oc = $current.substring(1).toLowerCase())
    #set($final = "$final$fc$oc")
class Controller_${final}


> Why the #if statement doesn't work.

The default "PHP Class" template is used via special dialog (New | PHP Class) where you can actually chose what will be created (class, interface or trait) and therefore corresponding file template will be used.

When you cloning/copying that template, it will be used without that custom dialog .. and therefore some special processing of certain variables will not be done. In such case you better to compare if variable is not empty -- try this kind of approach:

#if (${NAMESPACE} != "")

Please sign in to leave a comment.