A Tour of the Main PHP Features in Dreamweaver CS5
Let’s take a closer look at why Dreamweaver CS5 has become such a good development environment for beginners and more experienced PHP developers. If you’re completely new to PHP, it might be best for you to skim the rest of this lesson to get a flavor of what’s in store. Come back later to read each section in more detail when you’re more familiar with PHP to learn about particular features.
PHP features also in previous versions
For the benefit of newcomers to Dreamweaver, I’ll describe briefly the basic features inherited from previous versions before moving on to the advanced PHP features that are new to Dreamweaver CS5. In addition, I’ll explain how to set various options, so existing users will benefit from some of the information here as well.
Features discussed include:
- Line numbering
- Syntax coloring
- Balancing braces
- Code collapse
- Split Code view
- Applying and removing comment tags
- Live Code
When working with PHP scripts, it’s essential to be able to find a specific line, because PHP error messages always refer to the line where a problem was identified. By default, Dreamweaver displays line numbers in a column on the left of Code view.
If line numbers are not visible or if you want to turn them off, click the Line Numbers icon in the Coding toolbar. Alternatively, choose View > Code View Options > Line Numbers to toggle them on and off.
Line numbers refer to new lines created by pressing Enter/Return. By default, Dreamweaver soft wraps long lines in Code view. If you don’t want Dreamweaver to wrap lines of code like this, you can toggle the option on and off by clicking the Word Wrap icon in the Coding toolbar. Alternatively, choose View > Code View Options > Word Wrap.
Dreamweaver automatically colors different elements of PHP code to make them easier to identify. PHP tags and strings (text in quotation marks) are colored red, reserved keywords are green, functions are dark blue, and variables are a lighter blue. If part of your script is the wrong color, it’s an almost certain sign that there’s an error in your code; the most common cause is a missing or mismatched quotation mark.
If you want to change the default colors used by Dreamweaver, select the Code Coloring category in the Preferences panel. Select PHP in the Document Type field, and click the Edit Coloring Scheme button to open the following dialog box.
Don’t be confused that the first item in the “Styles for” list is for a different server-side technology (ColdFusion Script Tag). Just click in the Preview pane at the bottom of the dialog box, and Dreamweaver automatically highlights the appropriate PHP value in the “Styles for” list.
- Select the type of element you want to change in the “Styles for” list or the Preview pane.
- Click the color box next to “Text color” to select a new color.
- Use bold, italic, or underlined text, or any combination of them to change text.
- “Background color” applies a background color only to the selected type of element.
- To change the background color of Code view, click OK to close the Edit Coloring Scheme for PHP dialog box, and then click the color box next to “Default background” in the Code Coloring category in the Preferences panel.
Syntax coloring is turned on by default. It can be toggled on and off by choosing View > Code View Options > Syntax Coloring.
Dreamweaver CS5 supports PHP syntax coloring and code hints in files that use the following filename extensions: .php, .php3, .php4, .php5, and .phtml. It also recognizes Smarty templates (.tpl files) but treats them the same way as HTML files. Unless you have a specific reason for choosing a different filename extension, you should always use .php. However, if you need to use a filename extension that’s not on the list, you can get Dreamweaver to recognize it by following the instructions found at http://go.adobe.com/kb/ts_tn_16410_en-us.
Curly braces must always be in matching pairs, but there might be dozens or hundreds of lines of code between the opening and closing braces. Unlike some other editing programs, Dreamweaver does not automatically insert a closing brace when you type an opening brace, but Balance Braces is an indispensible visual guide.
With the insertion point anywhere between two braces, click the Balance Braces icon in the Coding toolbar to highlight the code enclosed by the braces.
Alternatively, choose Edit > Balance Braces, or press Ctrl+’/Cmd+’ (single quotation mark).
When working on a long script, it’s useful to be able to hide one or more sections of the code so you can see code that might be far from the section you’re currently working on. To collapse a section of code, select it, and click the minus box at the top or bottom of the selection. In the Mac version, the minus boxes are replaced by a down triangle at the top and an up triangle at the bottom. Click either triangle to collapse the selected code.
The collapsed section of code displays just a few characters from the first line in a dark gray box. Hover your pointer over the gray box, and Dreamweaver displays the first ten lines as a tooltip to remind you what the collapsed section contains.
Dreamweaver remembers which sections of code have been collapsed, even when you close a file. When you reopen it, the collapsed sections remain closed.
To expand a collapsed section, click the plus box (or right-facing triangle on a Mac) next to the gray box. If the plus box or triangle isn’t visible, click the gray box to bring it back into focus.
You can also expand all sections of collapsed code in a single operation by clicking the Expand All icon in the Coding toolbar. Alternatively, press Ctrl+Alt+E/Opt+Cmd+E.
Split Code view
Another useful way to view different parts of the same script is to use Split Code view. This opens the current document in Code view with the Document window split vertically or horizontally. Both sides of the Document window scroll independently, allowing you to access completely different sections of the same page. To access Split Code view, choose View > Split Code.
Applying and removing comment tags
Comments are useful not only for documenting your scripts, but also to disable a section of code while troubleshooting.
When you click the Apply Comment icon , you are presented with the following choice of five styles of comments.
The only options of value in a PHP script are /* */ and //.
The final option, <?php /*?> <?php */?>, is of limited use because you cannot nest PHP tags inside a PHP code block. Its only purpose is to comment out a section of HTML inside a PHP page and prevent the affected section from being sent to the browser. By contrast, an HTML comment remains visible in the browser’s source code view.
- To apply a multiline comment, select the code you want to comment out, click the Apply Comment icon, and choose Apply /* */ Comment from the menu.
- To apply a single-line comment, put the insertion point where you want the comment to begin, click the Apply Comment icon, and choose Apply // Comment.
By default, code that has been commented out is displayed in orange, making it easy to distinguish it from code that should be processed by the PHP engine.
The Remove Comment icon should really be called Remove Comment Tags. It removes the comment characters, but leaves everything else intact. It works like this:
- To remove the tags from a multiline comment, select the entire comment, including the /* at the beginning and the */ at the end. If you select less, nothing happens.
- To remove the tags from several multiline comments in a single operation, select at least from the first /* to the last */, and click the Remove Comment icon.
- Single-line comments embedded in multiline comments are not affected when the multiline tags are removed.
- To remove a single-line comment tag, set the insertion point anywhere inside the comment, and click Remove Comment.
Single-line comment tags are removed only when nothing else (except whitespace) precedes them on the same line. For example, the two forward slashes will be removed from the following line, even if there are spaces before the comment tag:
// echo ‘Hello, world!’;
However, they will not be removed from the following line, because the comment doesn’t affect the whole line:
echo ‘Hello, world!’; // this is a comment
This is the same as using View Source in a browser without launching your page in the browser. Everything is done inside the Dreamweaver Document window.
If you can’t see the Document toolbar, choose View > Toolbars > Document. You can also choose View > Live Code.
New and improved PHP features in Dreamweaver CS5
The features listed so far are all useful—essential, indeed—but would not be enough on their own to recommend using Dreamweaver CS5 as a serious PHP development environment. It’s the following improvements that really make a difference:
- Expanded code hinting for PHP core functions, classes, and constants
- Code hints for custom functions and classes
- Site-specific code hints
- Automatic recognition of classes and objects
- Autocompletion of defined variables
- Real-time syntax checking
- Dynamically related files
- Live View navigation
- CSS inspection
Code hinting for PHP core functions, classes, and constants
Dreamweaver CS5 code hints now cover all core elements of PHP 5.2, namely:
- Approximately 1,900 core functions
- About 170 classes and interfaces, including 800 related methods and more than 200 class properties
- Nearly 2,000 constants
If you’re wondering why PHP 5.3 isn’t supported, it’s because of the engineering time required to integrate the documentation into Dreamweaver. Yes, that’s right—documentation. Dreamweaver automatically displays the relevant help page from the PHP manual for a built-in function or class.
Most help pages include a description of the function or class with details of the arguments it takes, the values it returns, and the minimum version of PHP required. In addition, there are frequently code examples. And if that’s not enough, clicking the link at the top left of the documentation takes you to the equivalent page in the PHP online manual, which contains the most up-to-date information, as well as comments and tips added by other users.
The way in which code hints are selected has also been improved in three important ways:
- Code hints are not case sensitive. You can type in lowercase, and Dreamweaver automatically converts the selected value to uppercase for constants and superglobals.
- Underscores are automatically inserted. When you type $p, Dreamweaver automatically suggests $_POST as one of the options.
- You don’t need to start at the beginning. Dreamweaver constantly searches for substrings within code hints. For example, typing sep automatically selects all functions and constants that contain that sequence of letters, including the constants DIRECTORY_SEPARATOR and PATH_SEPARATOR.
With a little experimentation, you can create your own shortcuts for code that you use regularly. All you need to do is discover the sequence of characters that rapidly brings up the one you want. For example, typing gesi takes you instantly to getimagesize(). Dreamweaver recognizes the “ge” of “image” and the “si” of “size” as a unique sequence.
To activate code hints, press Ctrl+spacebar in a PHP code block. Even if you forget to do so before you start typing, press the same key combination without first pressing the spacebar, and Dreamweaver uses the preceding sequence of characters to select available choices.
As soon as Dreamweaver narrows down the available candidates, you can use your up and down arrow keys or your mouse to select the one you want. Press Enter/Return or double-click to insert the function or constant into your script.
Code hints for custom functions and classes
Dreamweaver CS5 doesn’t stop at built-in functions. It’s now capable of code introspection. This is just a fancy way of saying that Dreamweaver automatically inspects any custom functions or classes and builds code hints from them. Hints are available for functions and classes that are either declared in the same page or directly included in the page using one of the PHP include or require constructs. The following screenshot shows an example of custom code hints in action.
In this example, the file date_functions.inc.php contains a custom function called mdy2mysql(). Because it’s included in the current page through require_once, Dreamweaver automatically includes it in code hints that are displayed when you type the letters md. The list of code hints also indicates where the function is defined, making it clear that it’s a custom function.
When you select a custom function from the list of code hints, Dreamweaver displays the names of any arguments it expects.
Site-specific code hints
If you’re serious about working with PHP, you’ll probably want to use a framework. A framework is a library of predefined functions and/or classes that perform common tasks. The advantage of a framework is that the code has usually been developed and tested by very experienced people. Instead of reinventing the wheel, you can build sophisticated applications by writing very little code. All the complicated code is in the framework files.
The framework that I chose to use in later lessons is the Zend Framework (ZF). The “minimal” version of ZF 1.10 contains more than 2,700 files in nearly 500 folders. Fortunately, ZF has an autoloader that accesses only those files that are needed for a particular purpose. Unfortunately, the ZF naming convention leads to class names, such as Zend_File_Transfer_Adapter_Http, that are a nightmare to type—and remember. This is where site-specific code hints come to the rescue.
Site-specific code hints are designed to generate code hints for third-party frameworks, including the three most popular content management systems, WordPress, Drupal, and Joomla! The code hints are generated through code introspection in the same way as for custom functions and classes. The difference is that you don’t need to include the external files directly in the page you’re working on. Once you have set up site-specific code hints, Dreamweaver scans the necessary files automatically and generates the code hints on the fly. Hints are available even if the definition file isn’t directly linked to your page.
You’ll learn how to set up site-specific code hints for WordPress, Drupal, or Joomla! in Lesson 4. The setup for other frameworks, including ZF, is covered in Lesson 7.
Automatic recognition of classes and objects
Most of the time, there’s no need to press Ctrl+spacebar to get code hints for classes and objects. As soon as you enter a space after the keyword new, Dreamweaver presents you with code hints for all the classes it recognizes.
Typing -> after an object automatically brings up code hints for all public methods and properties associated with the object’s class.
Similarly, typing the scope resolution operator—a double colon (::)—after a class name displays all static methods and properties associated with that class.
Controlling PHP code hints
Being provided with so many code hints is great, but what if you don’t want or need them all? Dreamweaver CS5 gives you the option to disable some—or even all—of them.
To control which code hints are enabled, select the Code Hints category in the Preferences panel. Turn off those that you don’t need by deselecting the appropriate checkbox in the Menus section. Table 1.1 lists the PHP modules covered by each option.
Table 1.1 PHP Modules Covered by Code Hints
Core functions, keywords, and superglobals, plus the following modules that are normally enabled in a standard configuration of PHP: Ctype, cURL, Date/Time, Filter, GD (images), JSON, Multibyte strings, MySQL, MySQL Improved, PDO (PHP Data Objects), PCRE (regular expressions), Reflection, Sessions, SPL (Standard PHP Library), SQLite, Tokenizer
Encryption and Compression
Bzip2, Hash, Mcrypt, Mhash, OpenSSL, Zip, Zlib
IBM DB2, LDAP, MS Sql, oci8 (Oracle Call Interface), ODBC, PostgreSQL
DOM & XML hints
DOM, SimpleXML, SOAP, WDDX, XML Parser, XML Reader, XML Writer, XML-RPC, XSL
Miscellaneous functions and classes
BC Math, Calendar, EXIF, GetText, GMP, IMAP, MemCache, Mimetype, Shared Memory, Sockets, Tidy
If you’re not sure which to choose, deselect all except “Core functionality” and, possibly, “DOM & XML hints.” The other options are mainly for specialist use. On the other hand, unless you find having them all turned on affects you adversely, just leave them all selected. The code hints are there to help you. The large number of code hints doesn’t appear to slow down Dreamweaver, but this might vary depending on your computer’s specifications and other programs running at the same time.
Autocompletion of defined variables
PHP variables begin with a dollar sign, so as soon as you type $, Dreamweaver CS5 pops up a list of predefined variables. In previous versions, this behavior was limited to PHP superglobals, such as $_POST and $_GET. In Dreamweaver CS5, you get your own variables, too. Continue typing, and the list of code hints narrows down the candidates. This is a major time-saver. Not only that but PHP variables are case sensitive, which helps to avoid problems with using, for example, $name in one place and $Name in another.
Experienced developers will be delighted to know that autocompletion is aware of variable scope. This is the principle that variables declared inside a function are not visible outside that function, nor are variables declared outside a function affected by what happens inside a function unless their values are explicitly passed to and returned by the function. In practice, this means that if you declare a variable called $total outside a function, $total will not be included in the autocompletion candidates while you are working inside a function. Similarly, if you declare a variable called $output inside a function, it will be among the candidates only within the scope of the function.
It should be noted, however, that there are some limitations with code hints for variables. Dreamweaver doesn’t provide code hints for array keys. For example, let’s say you have the following array:
$colors = array(‘black’ => ‘#000’, ‘white’ => ‘#FFF’);
Dreamweaver will provide a code hint for $colors[, but after that, you’re on your own. You need to type ‘black’ or ‘white’ followed by the closing square bracket manually.
Real-time syntax checking
When you begin typing a PHP script in Dreamweaver CS5, you’ll immediately notice that the program gives you a syntax error. Even typing the first couple of characters of an opening PHP tag triggers an error message in the Info Bar at the top of the Document window and puts a red marker over the line number.
The red error markers remain visible even if you turn off line numbering. At first, this might seem like an overly aggressive attitude toward error checking, but if the marker doesn’t disappear when you get to the end of a statement, you know immediately that an error needs to be corrected. Errors are much easier to identify and correct as you go. No more round trips to the testing server to discover that a semicolon is missing or a mismatched quote exists somewhere deep in your script.
The Syntax Error Alerts in Info Bar icon in the Coding toolbar toggles the display of error messages on or off. Alternatively, choose View > Code View Options > Syntax Error Alerts in Info Bar.
Although this real-time syntax checking is smart enough to spot something wrong with your script, it won’t tell you what the problem is. That’s up to you. But knowing where to look for the problem makes troubleshooting a whole lot easier.
Dynamically related files
When you open a PHP file in Dreamweaver CS5, a narrow strip (the Info Bar) appears at the top of the Document window. If you haven’t yet defined a testing server, the Info Bar provides a link that opens the Site Setup dialog box (defining a site and testing server is covered in the next lesson). Otherwise, it informs you that the page might have dynamically related files that can only be discovered by the server.
By default, Dreamweaver displays only directly linked files in the Related Files toolbar. To display dynamically related files, click the Discover link in the Info Bar. The first time you do this, you will see a warning that Dreamweaver will execute any scripts included in the page. This is just Adobe being ultracautious. All it means is that Dreamweaver will parse the PHP in the same way as if you loaded the page into a web browser. Unless you want to see this warning every time you use dynamically related files, select the checkbox to not show the warning again, and click OK.
Dreamweaver connects to your testing server (which needs to be running) and compiles a list of dynamically related files. This might take a few seconds, depending on the complexity of the page and your site. The dynamically related files are added to the Related Files toolbar in the order they are discovered. If there are too many to fit, click the double chevron at the right end to display a list of all the files.
Filtering dynamically related files: A basic WordPress site uses no fewer than 65 dynamically related files, so you need to filter them to maintain your sanity. To do so, click the funnel-shaped icon at the right end of the Related Files toolbar, as shown here.
You can toggle on and off the display of .css, .php, and .xml files. However, a WordPress site has so many .php files, you need to narrow down the list to the ones you want, as follows:
- Click the funnel-shaped icon at the right end of the Related Files toolbar, and choose Custom Filter to open the Custom Filter dialog box.
- Type a list of files or filename extensions separated by semicolons into the text field. There should be no space around the semicolons.
Using the Custom Filter disables the other filter options, so you need to include all the files you want to work with. For example, the basic structure of a WordPress site consists of index.php, header.php, sidebar.php, footer.php, and any style sheets.
Use this as your custom filter:
You can also use an asterisk as a wildcard character. For example, wp* selects all files that begin with wp.
Live View is a browser within the Dreamweaver Document window. It uses the WebKit browser engine, which also drives Safari and Google Chrome. Although you can’t edit a page in Live View, you can use Split view and related files to edit the underlying code and styles, and see the effect instantly in the Document window.
When it was introduced in Dreamweaver CS4, Live View made it a lot easier to see how dynamic effects, such as rollovers, flyout menus, and CSS, would work. The big drawback was that you could see only the current page. Links didn’t work, nor did any of the popular CMSs, such as WordPress, Drupal, or Joomla!, that rely on dynamically related files.
All that has changed in Dreamweaver CS5. Live View now works like an ordinary browser—well, almost. The only difference is that you need to hold down Ctrl/Cmd to follow a link. There is an option on the Live View Options menu to follow links continuously, but this applies only to the current page. You need to select it again for each new page.
What makes Live View so powerful in Dreamweaver CS5 is that it follows links wherever they go, even if they lead to a live site on the Internet (assuming that you’re connected). Code view also shows the source code for related files on external sites, although they are read-only.
In addition, you can log into password-protected pages. The following screen shot shows the Dashboard of a WordPress site, which can be accessed only by submitting a username and password.
The icons on the Browser Navigation Bar work like an ordinary browser with Back and Forward arrows, Refresh, and Home—which takes you back to the page you originally loaded into the Document window. The Address text field remembers the URLs of pages you have loaded during the current session (but not those you have navigated to). This enables switching to another page without leaving Live View by simply clicking the down arrow at the right end of the Address field and selecting the URL. You can also type the URL of a remote site in the Address field to inspect it in Live View.
Live inspection of CSS layout
Yet another important new feature in Live View is CSS Inspect mode. Click the Inspect button on the Browser Navigation Bar, and mouse over the page. Dreamweaver highlights each page element as you pass over it, showing elements in blue, padding in violet, and margins in yellow.
Click the element in Live View to freeze the display. CSS Inspect mode combined with the CSS Styles panel or a style sheet selected from the Related Files toolbar provides a powerful way to inspect and edit CSS, particularly in a PHP site.