blob: 1a2f552d6d8edf42d27bab9686a39ab19eae1dfa [file] [log] [blame]
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
= Code Templates in NetBeans IDE for PHP
:jbake-type: tutorial
:jbake-tags: tutorials
:jbake-status: published
:syntax: true
:icons: font
:source-highlighter: pygments
:toc: left
:toc-title:
:description: Code Templates in NetBeans IDE for PHP - Apache NetBeans
:keywords: Apache NetBeans, Tutorials, 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.
== 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.
image::images/code-template-options.png[]
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 <<syntax,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:
* <<expand-with-abb,Expand the template>> by using the template abbreviation followed by the Tab key (or a different key or key combo that you define).
* <<expand-with-cc,Insert the expanded template>> by using code completion.
* <<surround-code,Surround your code>> with the template, by using the margin hint or Alt-Enter.
After you insert the template, the IDE helps you <<edit-parameters,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.
image::images/expand-template-on.png[]
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 <<expand-with-cc,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.
image::images/expanding-template-with-abb.png[]
. 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,Placeholder name section>>.
image::images/select-constructor-name.png[]
. 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-name,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.
image::images/insert-template-with-cc.png[]
. Select the new class template and press Enter. The IDE inserts it into your code.
. 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.
image::images/select-constructor-name.png[]
. 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`` &amp; ``catch``
* ``foreach``
* ``for``
* ``ob_start`` &amp; ``ob_end_clean``
In addition, you can <<create,create a new template>> that can surround code if the template includes the `allowSurround` <<complex,parameter hint>>. (Hat tip to the link:http://www.mybelovedphp.com/2012/05/14/tips-for-using-the-netbeans-editor-for-kohana-and-kostache-mustache-templates-using-surround-with/[+ 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 image:images/hint-icon.png[] icon.
*To surround code with an if(true) template:*
1. Create a PHP block with the variables ``$a = true`` and ``$b = 10`` .
[source,php]
----
<?php
$a = false;
$b = 10;?
>
----
. Select the line ``$b = 10;``
image::images/selected-variable.png[]
. Click the Hint image::images/hint-icon.png[] icon or press Alt-Enter. The Surround with... dialog opens.
image::images/surround-hint.png[]
. Click `` Surround with if{*true*){...``
image::images/surround-if-true.png[]
. The IDE surrounds the line ``$b = 10;`` with an ``if(*true*){... `` template.
image::images/inserted-if-true.png[]
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 <<complex,Parameter defined by hints>>.
image::images/change-condition.png[]
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.
image::images/cursor-after-not-editing.png[]
image::images/cursor-after-editing.png[]
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.
image::images/iter-cc.png[]
. The iteration has two variables as parameters, ``$index`` and ``$array`` . ``$index`` is selected automatically for editing. (Pressing Tab moves between parameters.)
image::images/iteration1.png[]
Type ``i`` . All three instances of ``$index`` change to ``$i`` .
image::images/iteration2.png[]
. Press Enter or Tab. The parameter ``$array`` is selected.
. 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:*
. In an empty PHP block, type the follwing code:
[source,php]
----
<?php
$arr = array(new ArrayIterator($array()), new ArrayObject($array()));?>
----
. After the line declaring the ``$arr`` array, type ``fore`` and use code completion to insert the `` foreach`` template (abbreviation: ``fore`` ).
image::images/cc-foreach.png[]
. 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.
[source,php]
----
<?php
$arr = array(new ArrayIterator($array()), new ArrayObject($array()));
foreach ($arr as $value) {$value}?>
----
. After ``$value`` , type ``->`` . Code completion offers you the correct methods for the ``$value`` variable, which is derived from the array ``$arr`` .
image::images/value-method-cc.png[]
== 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:
* An arbitrary <<placeholder,placeholder name>>, such as ``${SomeName}``
* A <<reserved-name,reserved name>> that gives processing instructions to the IDE
* A descriptive parameter name and a set of <<complex,hints that define the parameter>>
* <<pre-defined,Pre-defined parameters>>.
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 [examplecode]# ``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 <<define,Defined PHP Templates>> and <<expand-with-abb,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.
image::images/expanding-template-with-abb.png[]
=== 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 <<define,Defined PHP Templates>> and <<expand-with-abb,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}`` .
[source,php]
----
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).
image::images/cursor-position-changes.png[]
=== Parameter defined by hints
Parameters can consist of an arbitrary, descriptive name in ALL-CAPS and one or more hints.
[source,php]
----
${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.
[source,php]
----
$$${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 <<surround-code,surrounding your code with a template>>. The expanded text of this template is
[source,php]
----
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...
image::images/selected-variable.png[]
...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`` .
image::images/inserted-if-true.png[]
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,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.
image::images/code-template-options.png[]
. Click New to open the New Code Template dialog box. Type in the abbreviation you want for the template and click OK.
image::images/new-abb.png[]
. 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 <<syntax,PHP Code Template Syntax.>>
image::images/new-abb-text.png[]
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 link:http://forums.netbeans.org/php-users.html[+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: |
[source,php]
----
<?php echo ${cursor}  ?>
----
|===
image::images/uc-php.png[]
== 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: |
[source,php]
----
defined('_JEXEC')or die('Restricted access');${cursor}
----
|===
image::images/uc-joomdef.png[]
== 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: |
[source,php]
----
$$${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}
----
|===
image::images/uc-mycon.png[]
== 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: |
[source,php]
----
public function ${functionName}Action () {${selection}${cursor} }
----
|===
image::images/uc-zfact.png[]
=== 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: |
[source,php]
----
$$${ELEMENT newVarName default="element"} = new Zend_Form_Element_Submit('submit', array('label' => 'Send data to server')); $$this->addElement($$${ELEMENT}); ${cursor}
----
|===
image::images/uc-zelement.png[]