Thứ Bảy, 10 tháng 5, 2014

Improving your productivity with Eclipse PDT

Getting Started

 Overview


Eclipse PDT is an eclipse plugin which provides a fully featured IDE for PHP development. Most modern frameworks make heavy use of new language features like traits (5.4) and namespaces (5.3) and PDT supports those features out of the box.  

This tutorial describes how to setup and use PDT to get the most out of it for your PHP projects and increase your productivity.

The first part deals with installation, configuration and the basics of editing and navigating PHP sourcecode with eclipse PDT.

While this part contains very basic topics, during the following parts i will give an in-depth explanation of more advanced features, like debugging, buildpath/includepath management, integrating composer or unit testing with PHPUnit.

Prerequisites

As Eclipse is built with Java, you will need the Java Runtime Environment. Some PDT features need to execute PHP scripts, which is why it is recommended to have a fully working PHP commandline setup too.

Installation

Although PDT is compatible with older versions of eclipse, it is recommended to use the latest eclipse version - which is Juno 4.2 SR1 at the time of this writing.

Install Eclipse

Installing Eclipse is as simple as downloading the binary, unpacking and running it. The Eclipse download page provides various flavours of eclipse packages, but for PDT it’s best to simply use the “Eclipse Classic 4.2.1” package.

A note on performance

Eclipse ships with a configuration file called "eclipse.ini" which contains important parameters like how much Java Heap Space is available to eclipse and similar stuff. From my experience, when working with larger projects these settings might not be high enough.

To change this, you can manually alter the .ini file. The location of this file depends on your operating system:

  • Windows/Linux: It's in the root path of the unpacked eclipse folder
  • Mac: You need to right-click the Eclipse application -> "Show Package Contents" and browse to "Contents -> MacOS"
 Caution: Before altering this file, be sure to make a backup of it. If it contains invalid values, eclipse will not be able to start!

The important part in the .ini file are the values "-Xms" and "-Xmx". To understand what changing these values means, here's the explanation from oracle:

The -Xms option sets the initial and minimum Java heap size.  
The -Xmx  option sets the maximum Java heap size.
The Java heap (the “heap”) is the part of the memory where blocks of memory are allocated to objects and freed during garbage collection.

By default, they are set to "-Xms40m" and "-Xmx512m". So we get a minimum heap size of 40MB and a maximum heap size of 512MB. My computer has 16GB of memory, so i've set the values higher - to "-Xms256m" and "-Xmx1024m". Depending on your amount of available memory, you might tweak those settings accordingly.

Additionally, you can add the "-XX:MaxPermSize=256m" parameter below the "-Xmx" parameter. This will increase the "permanent generation" memory block and can also increase performance.

The above changes to the eclipse.ini are not mandatory, but recommended to gain performance improvements, as the shipped defaults are quite low.

Install PDT

When it comes to installing PDT, you have 2 options: Stable or nightly build. The stable build is kept in sync with the eclipse release cycle. Next scheduled release date is February 22, 2013.

As this tutorial will walk you through the usage of additional plugins which extend PDTs functionality, i’d recommend to use the nightly build, because some of those additional features are developed in sync with the PDT nightlies.

To install PDT nightly builds, open "Help -> Install New Software" in Eclipse, enter the following URL


and select “PHP Development Tools (PDT)” from  the “PHP Development Tools” category. If you use Mylyn, you can optionally add the “PDT Development Tools (PDT) Mylyn Integration”.


Install PDT Extensions Core-Plugin

The PDT-Extension-Group is an effort of PDT extenders to provide a centralized PDT extender platform, and as one of the main parts of this effort stands the PDT Extensions Core Plugin.

This plugin provides additional PDT features like class/interface generation wizard, getter/setter generation, PSR-1/2 compliant formatter, PHP CodingStandard Fixer integration and additional validation and quickfixes.

To install it, add the following URL to your eclipse updatesites:


and install the “PDT Extensions” plugin under the “PDT Extensions” category.

Note that the pdt-extensions updatesite provides additional features and plugins like support for various frameworks, PHPUnit, Composer and a variety of text editors. You can read more about all the available features by visiting the updatesite URL.

Initial Setup

Now that everything is installed, you can switch to the newly available “PHP” perspective. Before we start though, you should do some initial configuration of your workspace. Eclipse and PDT provide a large number of preference options. This tutorial will walk you through the most important ones.  Remember that this needs to be done only once after the initial installation.

General settings

Open up the eclipse preferences and collapse the “General” node. You’ll find some useful options here regarding the behavior of eclipse itself.

  • Editors -> Text Editors: Set the global tab policy (Spaces/Tabs, number of spaces, etc)
  • Web Browser: Select the browser used when eclipse opens an URL - this will be useful when working with the debugger which is explained in part 3)
  • Workspace: Set the Text file encoding and line delimiter characters

PDT settings

Open up the eclipse preferences and collapse the “PHP” node. Most PHP settings can be set on a global scope and overridden on a project level. Here are the most important PHP settings for now:

  • PHP Executables: Manage the available PHP executables on your system. These are used by PDT when it needs to launch php scripts, so you should provide at least one executable. I’ll go into the details of this in the next part of the tutorial.
  • New Project Layout: This lets you define how newly created projects are configured. I'd recommend to use "Create separate folders for source files and public resources" for now. Next part of the tutorial will go into details why this is useful.
  • Debug: Set the default debugger to use. You can leave this as is for now, part 4 of the tutorial will get into this in detail.
  • Code Style -> Formatter: Choose from built-in code formatter profiles or create your own one.
  • Editor -> Syntax Coloring: Change the way your sourcode is colored. Note that the pdt-extensions updatesite provides a mirror of the “eclipse color theme” feature, which offers an extensive palette of themes.

As you can see there’s tons of other preferences available. Most of them should be fairly self explanatory.


Your first project


After setting everything up to have a sane workspace, you can now go ahead and create your first project (File -> New -> PHP Project). You can leave everything as is for now in the “Create a PHP Project” dialog and simply enter the name of your project and click “Finish”.


Your new project should contain the following entries:

  • application
  • public
  • PHP Include Path
  • PHP Language Library

The meaning of the last 2 entries will be explained in the next part of the tutorial, you can focus on the “application” folder for now, which will contain our application code. You can of course change the name of the default source folder under the "New Project Layout" preference node.

The PHP Explorer


The left view of your PHP workspace contains the PHP Explorer which provides a tree browser for all your projects in your workspace. The top toolbar has a small icon with yellow left and right arrows. Activating this icon will link the currently open PHP script with the corresponding node in your PHP explorer. The small arrow on the right side of the toolbar lets you select available filters for the PHP explorer as well as define “Working sets”.

As we want to be standard compliant, we’ll choose to structure our project to work with the psr-0 autoloading standard. To do so, we’ll create the following folder structure:

  • application
    • Acme
      • Demo
        • Auth

Meaning "Acme" is our imaginary vendor name, "Demo" the project name and the Auth folder will contain our authentification related code which we’ll begin with.

Using the PHP Structured Editor


Let’s start with defining an interface for our user classes. Right-click on the “Auth” folder and select “New Interface”. Use “UserInterface” as the interface name, “Acme\Demo\Auth” as the namespace and click “Finish”.






As the next step, define a function called “getUsername()” in the newly created interface. 





Now we want to create an abstract base class which implements our interface. Right-Click on the “Auth” folder, and choose “New Class”.  Choose “BaseUser” as name, select the “abstract” modifier checkbox. In the Namespace field, add “Acme\Demo\Auth” - note that now you’ll get codeassist for the already existing namespace, so you don’t need to enter the whole namespace by hand anymore. In the “Interfaces” box, click “Add” and choose our “UserInterface”. 





This will result in the following generated code:




Annotation markers


Based on the code for our BaseUser class, let’s look at the editor a little closer. To the left and right side of the editor you’ll see 2 vertical bars containing editor annotations. These annotations can be very handy in larger projects / files, so let’s go through them:

In the left bar, right to the line numbers, you can use the +/- icons to fold/unfold parts of your code - based on PHP scopes. Which parts should be folded by default can be configured in the PHP preferences section.

Left to the line number bar you’ll see different markers, and if you place the curser somewhere inside the class, you’ll also notice a vertical blue line. The blue line annotates the scope the cursor is currently placed in. Try it: click on the class name, and you’ll see how the blue line changes and  marks the beginning of the class scope until the end of the class scope.  Pretty useful to quickly check scopes when browsing through larger PHP classes.

Additionally to the scope annotation, you’ll see a small marker with a little “arrow icon”, and another marker with a “check” icon.

The up-arrow annotates a method wich implements an interface method. If you override a superclass method, you will get a green arrow instead.

The check-marker annotates a TODO task tag. These Markers can be viewed across your workspace in a special view called “Tasks”. Let’s go ahead and open this view: Window -> Show View -> Tasks.

This view will list all TODO and FIXME markers in all of your PHP classes. Double clicking an entry in the view will open the corresponding source file. Try it: Add a comment somewhere in your getUsername() function:

// FIXME implement this method.  

You will get an additional FIXME Task tag inside the Tasks view.

Tip: If you use Mylyn you can even create tickets based on those task markers in your favorite issue tracker from within eclipse.

Editing source code

“Pretty obvious, not worth mentioning” i hear you say. Well, you’re probably right, but maybe this brief list will contain the one or other shortcut you didn’t know yet. (Cmd/Ctrl means either Cmd on Mac or Ctrl on Windows / Linux).

  • Moving blocks of code: Press Alt+Up/Down Arrow to move blocks of your code up and down. This works also with multiline selections.
  • Duplicate blocks of code: Press Alt+Cmd/Ctrl+Down/Up Arrow to duplicate a block of code upwards or downwards.
  • Deleting a line: Press Cmd/Ctrl+D to delete a line of code
  • Vertical Editing Mode: To enter vertical editing mode (edit multiple lines at once), press Cmd+Alt+A (Mac) or Alt+Shift+A (Windows/Linux)
  • Generate element comment: Press Ctrl/Cmd+Shift+J while having the curser placed over a PHP element like a class or function to generate a phpDocBlock comment for the element.
  • Format the current sourcefile: Ctrl/Cmd+Shift+F 
  • Word completion: By pressing "Ctrl + ."  (Ctrl + dot) you can switch through word completions from words contained in the current document. This is not restricted to PHP types but to simple text. 
  • Jump to line: Ctrl/Cmd + L
  • Triggering codeassist: Codeassist will trigger automatically when available after 200 milliseconds. This can be changed in the preferences under “PHP -> Editor -> Content Assist”. To trigger it manually, press Ctrl + Space.


All keyboard shortcuts can be customized in the eclipse preferences under "General -> Keys".

 

Navigating through your project

Navigation is one of my favorite features of Eclipse in general. If you know how to use it properly, it can greatly improve your productivity.


  • Ctrl/Cmd+Click Navigation: When press Crtl/Cmd while clicking on a PHP element, PDT will open the corresponding declaration of that element. Try to click on the word “UserInterface” after “implements” in the BaseUser class: PDT will open the UserInterface source file for you and place the cursor on the interface definition. The keyboard-only equivalent of ctrl+click browsing is pressing F3 on any PHP element.
  • Navigating back and forth: When navigating through your project, you can use the yellow Left/Right arrows in the top toolbar of eclipse to quickly jump to the last edit location or the previous opened file.
  • Show type hierarchy: When pressing Ctrl+T inside a class, a type hierarchy popup will open. You can navigate the type hierarchy and open superclasses / interfaces from the current file.
  • Show quick outline of class: Ctrl + O opens a quick outline of the current source file allowing you to quickly navigate to another method / type.
  • Open Type: Cmd/Ctrl+Shift+T will open a Type selection dialog, allowing you to browse all of your classes/interfaces/traits available in your workspace and quickly navigate to it.
  • Open Method: Cmd/Ctrl+Shift+M will open a method selection dialog, allowing you to browse all of your methods defined anywhere in your workspace.
  • Open Resource: Cmd/Ctrl+Shift+R will open a resource selection dialog. This dialog lets you search through all files in your eclipse workspace quickly, not restricting them to PHP types.


Additional Views

There are some additional PHP views available which are not added to the PHP perspective by default. You can add them manually by clicking “Window -> Show View -> <VIEWNAME>”

PHP Project Outline

This outline shows a quick overview over the following elements of your PHP project:

  • Classes
  • Constants
  • Functions
  • Namespaces

PHP Functions


This view show a browsable and filterable list of the complete standard PHP API. You can right click any element to open the corresponding PHP manual webpage or double click to insert the element at the current cursor position.

 
Conclusion

After completing the first part of the tutorial you should have a good understanding of how to use the basic features of PDT like creating and editing resources and navigating through your project. 

The next part will focus on how to get the most out of the IDE features like codeassist and validation by introducing you to the concept of buildpaths and includepaths and an overview of the underlying technology.

If you know any other editor/navigation related tips and tricks, please leave a comment and i'll update this post accordingly.

Should you be running into troubles using PDT, you can always approach the community via the main communication channels:


Không có nhận xét nào:

Đăng nhận xét

Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...