Code Templates in NetBeans IDE for PHP

Code templates are prewritten snippets of code provided by NetBeans IDE. You can paste a snippet into your code by using code completion or the template's abbreviation followed by the Tab key. You can also surround your code with appropriate PHP snippets. Finally, you can define your own code templates. This tutorial shows how to use code templates and suggests useful cases for defining your own code templates.

Contents

Content on this page applies to NetBeans IDE 7.2, 7.3, 7.4 and 8.0

To complete this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE PHP download bundle
Java Development Kit (JDK) 7 or 8

 

Defined PHP Code Templates

To view the code templates that are defined in NetBeans, open Tools > Options (NetBeans > Preferences on Mac), select the Editor features, and select the Code Templates tab. To see the PHP code templates, select PHP in the Languages drop-down list. A table appears of code template abbreviations and expanded texts. If you select a code template in the table, its expanded text appears in the Expanded Text tab.

PHP code templates in the Options window, with the cli template selected

In this image the new class (cls) code template is selected, and in the Expanded Text tab you see what the template looks like when it's expanded. In the next section, you use the Tab function to expand this template in your code.

Note: The syntax of the new class (cls) code template is explored in the section PHP Code Template Syntax.

Using PHP Code Templates

There are three ways to insert code templates in your PHP code. Each way of inserting code templates is useful in different situations. The three ways to insert code templates are:

After you insert the template, the IDE helps you edit parameters in the expanded template code.

Expanding the code template by using the abbreviation + Tab

Look again at the Code Templates tab in the Options dialog. At the bottom there is a drop-down field for selecting the Expand Template On key-combo. This is the key-combo you press after typing in the code template's abbreviation in order to expand the code template. By default the Tab key is selected but you can select other combos instead.

Expand Template On drop-down box

The rest of this section assumes that you have the default Tab key selected in the Expand Template on: field.

When the abbreviation for a template is also part of a keyword for code completion, it may be difficult to expand the abbreviation. In this case it is easier for you to use code completion to insert the template.

To expand the new class code template using its abbreviation + Tab:

  1. Create an empty PHP file.
  2. In the PHP block of that file, type cls and press Tab. The cls code template expands.

    Caution: Spell the abbreviation correctly! Expansion does not work if you misspell the abbreviation.

    Expanding a code template
  3. The placeholder class name (class_name) is selected automatically. You can move between placeholders by pressing Tab. You can immediately type the name you want for the class and this name overwrites the placeholder. Press Enter when you are done and the IDE selects the name of the first function, which in this case is the constructor.

    Note: Placeholder names are discussed in more detail in the Placeholder name section.

    Constructor function name selected after class name edited
  4. Edit the function name or accept the default. Press Enter again, and the cursor moves to the inside of the function's body. In a real world scenario, you would now start coding the function and the rest of the class.

    The final position of the cursor is determined by the ${cursor} parameter. This parameter is described in the section Reserved names.

Inserting the code template with code completion

To insert a code template by using code completion, type the beginning of the expanded snippet (not the template abbreviation). The code completion dialog opens, showing you the snippet.

To insert the new class code template using code completion:

  1. In the PHP block of a PHP file, type cla.
  2. Wait for the code completion dialog to open.
  3. Locate the new class template, which is listed with its abbreviation (cls). The PHPDoc frame shows the expanded template.
    Code completion dialog showing new class template
  4. Select the new class template and press Enter. The IDE inserts it into your code.
  5. The placeholder class name (class_name) is selected automatically. You can move between placeholders by pressing Tab. You can immediately type the name you want for the class and this name overwrites the placeholder. Press Enter when you are done and the IDE selects the name of the first function, which in this case is the constructor.
    Constructor function name selected after class name edited
  6. Edit the function name or accept the default. Press Enter again, and the cursor moves to the inside of the function's body. In a real world scenario, you would now start coding the function and the rest of the class.

Surrounding code with a template

You can surround your code with the following PHP templates:

  • while
  • do
  • switch
  • if / elseif
  • try & catch
  • foreach
  • for
  • ob_start & ob_end_clean

In addition, you can create a new template that can surround code if the template includes the allowSurround parameter hint. (Hat tip to the My Beloved PHP blog.)

To surround code with a template, select the code and open the Surround with... dialog. To open the Surround with... dialog, either press Alt-Enter or click the Hint Hint icon icon.

To surround code with an if(true) template:

  1. Create a PHP block with the variables $a = true and $b = 10.
    <?php
    $a = false;

    $b = 10;
    ?>
  2. Select the line $b = 10;
    Selected variable $b = 10
  3. Click the Hint Hint icon icon or press Alt-Enter. The Surround with... dialog opens.
    Open surround-with dialog
  4. Click Surround with if{true){...
    Surround-with dialog with Surround with if(true) selected
  5. The IDE surrounds the line $b = 10; with an if(true){... template.
    Inserted if (true) template

The IDE automatically inserts the nearest preceding suitable variable as the if statement's condition. In this case, that variable is $a, because $a is a boolean and the if(true){} statement takes a boolean variable as its condition. Furthermore, the condition is automatically selected for editing, in case the variable that the IDE inserts into the condition is not the correct variable. This means you can begin typing the correct variable immediately after the template is inserted. Code completion can help you select the correct variable in this case.

Note: The if(true){} template is described in detail in the section Parameter defined by hints.

Selecting the variable to use as a condition, from code completion

Press Enter to exit the statement's condition. The cursor moves to the appropriate location, which in this case is the end of the line $b = 10;. You can edit the condition and press Enter or accept the automatically inserted condition and press Enter. In either case the cursor exits the condition and moves to the appropriate location.

Cursor after not editingCursor after editing

The next section contains more details about editing the parameters in expanded templates.

Editing parameters in expanded templates

In the sections on inserting templates into your code, you saw how the IDE automatically selected the class name for editing when you expandede the new class template, and how the IDE automatically selected the condition name for editing when you expanded the if(true) template. Now you will see some more ways the IDE helps you edit parameters in expanded templates.

To simultaneously edit multiple instances of a parameter:

  1. In an empty PHP block, type for and press Ctrl-Space to open code completion. Select the iteration template (abbreviation iter) and press Enter. A new iteration is inserted into your code.
    Code completion showing iteration template selected
  2. The iteration has two variables as parameters, $index and $array. $index is selected automatically for editing. (Pressing Tab moves between parameters.)
    Inserted iteration line with parameters, with $index parameter selected for editing

    Type i. All three instances of $index change to $i.

    Inserted iteration line with parameter $index changed to $i
  3. Press Enter or Tab. The parameter $array is selected.
  4. Press Enter. The cursor enters the method body of the iteration.

The variable name refactoring feature in NetBeans enables you to change all instances of a variable name by editing only one instance. You see here how this is helpful when applied to template parameters.

The NetBeans IDE PHP editor also helps identify the correct method for variables.

To associate a variable in a template with the correct method:

  1. In an empty PHP block, type the follwing code:
    <?php

    $arr = array(new ArrayIterator($array()), new ArrayObject($array()));

    ?>
  2. After the line declaring the $arr array, type fore and use code completion to insert the foreach template (abbreviation: fore).
    Code completion for inserting the foreach template
  3. Place the cursor in the body of the foreach function (you can press Enter twice to move the cursor there) and type $value, or only type $ and select $value from code completion.
    <?php

    $arr = array(new ArrayIterator($array()), new ArrayObject($array()));

    foreach ($arr as $value) {
    $value
    }

    ?>
  4. After $value, type ->. Code completion offers you the correct methods for the $value variable, which is derived from the array $arr.
    Code completion for the $value variable, where $value is an Array Iterator method

PHP Code Template Syntax

NetBeans IDE provides code templates for all the languages it supports. Some of the syntax is general for all languages. Other syntax is specific to a language. In this section, you see the most relevant general template syntax and the syntax specific to PHP templates.

A PHP code template can contain PHP code and template parameters. A PHP template may consist of only PHP code, only parameters, or both code and parameters.

The syntax of a code template parameter is a dollar sign, $, followed by the parameter's definition between curly brackets {...}. Within this syntax, template parameters have one of four forms:

The following sections discuss each form of a code template parameter.

Note: $$${VARIABLE...} Sometimes you see a PHP code template where the syntax seems to be three dollar signs followed by curly brackets $$${...}. In this case, the code template includes a variable and its name. The syntax here is an escaped dollar sign, written as a double dollar sign $$, followed by a parameter for the variable name, ${VARIABLE...}. For example, the code template catch ${Exception} $$${exc} is expanded as catch Exception $exc.

Placeholder name


In the simplest case, a code template parameter is an arbitrary placeholder value. When the template is expanded, the IDE selects this placeholder name for editing.


For example, consider the new class template (cls) that this tutorial shows in the sections Defined PHP Templates and Expanding the code template by using the abbreviation + Tab. The expanded text of the new class template begins class ${className}. Here, the word class is PHP code and ${className} is a parameter. This parameter is only an arbitrary placeholder value for the name of the class. When the IDE expands the template, ${className} becomes class_name. The IDE expects that class_name is only a placeholder value and automatically selects this value for you to edit.

Expanding a code template

Reserved names

The IDE reserves two parameter names for use as operating instructions.

  • ${cursor} defines the location of the cursor after you finish editing all automatically selected values in the expanded template.
  • ${selection} defines a position for pasting the content of the editor selection. This is used by so-called 'selection templates' that appear as hints whenever the user selects text in the editor. If a template includes ${selection}, it usually refers to the same location as ${cursor}.

For example, again consider the new class template (cls) that this tutorial shows in the sections Defined PHP Templates and Expanding the code template by using the abbreviation + Tab. It contains two placeholder name parameters, ${ClassName} and $__construct. In the function body, it has the parameters ${cursor} and ${selection}.

class ${ClassName} {

function ${__construct} {
${selection}${cursor}

}

}

After the template expands, the placeholder class_name is selected automatically (1). Press Enter, and the placeholder __construct is selected automatically (2). There are no other values to edit. Press Enter again, and the cursor moves to the location indicated by ${cursor} in the template's text (3).

Three code snippets showing cursor position change from placeholder name to placeholder name to ${cursor} position

Parameter defined by hints


Parameters can consist of an arbitrary, descriptive name in ALL-CAPS and one or more hints.

${PARAMETER_NAME hint1[=value] [hint2...hint n]}

The name does not appear anywhere in the code. However, it is useful if you want to use the parameter more than once in a code template. You only have to define the parameter the first time, and can refer to it by name all subsequent times. For example, in the following code template the parameter ${CONLINK} is defined only the first time but is referred by its name two more times.


$$${CONLINK newVarName default="link"} = mysql_connect('localhost', 'mysql_user', 'mysql_password');  
if (!$$${CONLINK}) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($$${CONLINK});
${cursor}

Hints help the IDE to compute the value of the template parameter when the IDE expands the code template. For example, look at the if(true) template, which is used in this tutorial in the section on surrounding your code with a template. The expanded text of this template is

if (${CONDITION variableFromPreviousAssignment instanceof="boolean" default="true"}) {
${selection}${cursor}
}

Examine the parameter ${CONDITION variableFromPreviousAssignment instanceof="boolean" default="true"}. This parameter sets the condition of the if statement. Therefore the parameter is named CONDITION. The first hint is variableFromPreviousAssignment and the second hint is instanceof="boolean". Together, these two hints tell the IDE to look for the closest boolean variable that is assigned in the code previous to the code template. Add the third hint, default="true", and the parameter sets the condition as "if the closest previous boolean variable's value is true."

For example, when the line $b = 10 in the following code snippet is surrounded by an if(true) code template...

Snippet $a = false $b = 10

...the IDE looks for the closest boolean variable that was assigned previously, finds $a, and generates an if statement with the condition $a[=true]. The condition is automatically selected for editing, so the PHP programmer can change $a to another variable or to !$a.

Expanded template if $a=true then $b=10, with condition $a=true selected for editing

The following table lists the hints used in PHP code templates and descriptions of the hints.

Hint Description
newVarName The parameter value should be a 'fresh' unused variable name. Usually used with default.
default="" The default value of the parameter.
instanceof="" Type of PHP variable defined in the parameter.
variableFromPreviousAssignment The parameter value is the closest previously assigned variable. Usually used with instanceof and default.
variableFromNextAssignmentName The parameter value is the name of the closest variable assigned after the code template. Usually used with default.
variableFromNextAssignmentType The parameter value is the type of the closest variable assigned after the code template. Usually used with default.
editable=false The parameter value cannot be edited after the template is expanded.
allowSurround Allows the template to be used to surround code.

Creating Your Own Code Templates

You can create your own code templates in NetBeans IDE. This section tells you how to create code templates, explores their syntax, and suggests some useful templates to create.

To create a code template:

  1. Open Tools > Options (NetBeans > Preferences on Mac), select the Editor features, and select the Code Templates tab.
    PHP code templates in the Options window, with the cli template selected
  2. Click New to open the New Code Template dialog box. Type in the abbreviation you want for the template and click OK.
    New Code Template dialog asking for template abbreviation
  3. A new row is added to the table of code templates. This row contains only the abbreviation you provided. The cursor is in the Expanded Text tab, where the IDE placed the cursor automatically. You can begin typing the template's code immediately.

    Note: To learn about the syntax of the code template's expanded text, see the section PHP Code Template Syntax.

    Typing the expanded text of the new abb template

The following sections describe some use cases for creating your own PHP code templates. If you have any further use cases to suggest, please share them with the community at the PHP Users' Forum.

Use case: Inserting PHP into HTML

If you frequently insert PHP snippets into a block of HTML, you can create an HTML code template that inserts the PHP without you typing <?php ?> again and again.

The following code template inserts a PHP echo statement into HTML.

Language: HTML
Abbreviation: php
Expanded text:
<?php echo ${cursor}   ?>

Options window showing new php in html template

Use case: Joomla

Code templates can help you use PHP frameworks in NetBeans IDE, especially frameworks that do not have built-in support. Here is a code template one user developed to use with Joomla.

Language: PHP
Abbreviation: joomdef
Expanded text:
defined('_JEXEC')
or die('Restricted access');
${cursor}

Options dialog with new joomdef code template

Use case: MySQL connection

PHP developers often need to create a connection to a MySQL database. This code template creates one for you. The variable assigned to the MySQL connection has the placeholder name link. Note the use of the "triple" dollar sign $$$--really a double dollar sign, which produces a single dollar sign when expanded, followed by the parameter for the variable name.

Language: PHP
Abbreviation: my_con
Expanded text:
$$${CONLINK newVarName default="link"} = mysql_connect('localhost', 'mysql_user', 'mysql_password');  
if (!$$${CONLINK}) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($$${CONLINK});
${cursor}

New code template for MySQL connection

Use case: Action in Zend controller

Rather than use the NetBeans wizard for creating an action, you can use a code template to insert an action in a Zend Framework controller, such as indexController{}.

Language: PHP
Abbreviation: zf_act
Expanded text:
public function ${functionName}Action () {
${selection}${cursor}
}

New Zend action code template

Use case: Zend form element

This template inserts an element into a Zend form. Use it after you generate a form by calling the Zend create form <name> command.

Language: PHP
Abbreviation: zf_element
Expanded text:
$$${ELEMENT newVarName default="element"} = new Zend_Form_Element_Submit('submit', array('label' => 'Send data to server'));  
$$this->addElement($$${ELEMENT});
${cursor}
New code template for Zend Framework elements to insert in ZF forms

 


See Also

For more information about PHP technology on netbeans.org, see the following resources:

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE PHP development features, join the mailing list.

get support for the NetBeans

Support


By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2013, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo