Phalanger for Mono users

What is Phalanger?

Project Phalanger is PHP language compiler for the .NET Framework platform and starting from the 2.0 version also for the Mono platform. Phalanger was originally developed only for .NET (part of the version 1.0 was written in Managed C++), but one of the goals of the 2.0 version is full Mono support and ability to execute PHP applications on the Apache web server (using the mod-mono module). Phalanger is developed under the Shared Source license, which allows its modification and redistribution including commercial usage. For more information you can find the full license text at the CodePlex server.

PHP is a dynamic programming language, which means that its compilation to native code is very difficult. Because PHP was developed as scripting language it is more suitable for interpretation, which is what the standard PHP interpreter does. Phalanger follows the middle way - it compiles everything that can be compiled and the rest that is known only at runtime (for example calls to the eval function) is compiled later, when it is needed.

What is interesting about Phalanger?

Two key goals of the Phalanger project is to keep as good compatibility with the existing PHP applications as possible and very efficient execution. In the 2.0 version we also focused on the interoperability with the rest of the .NET/Mono world, which includes a few extensions to the PHP language (you’ll see some of them later in this article) and it makes it possible to use any .NET/Mono library from the application written in the PHP language. The following list shows some interesting possible Phalanger uses:

  • Execution of existing PHP applications - Phalanger is able to execute existing PHP applications two-times faster than standard PHP interpreter. For more information see the Benchmarks page. We tested several well-known PHP applications with Phalanger including PhpBB, PhpMyAdmin and DokuWiki.
  • PHP and Mono integration - Thanks to the Phalanger, it is possible to develop part of the application in any Mono language and to use these components in web application written using PHP. For example data access layer or working with web service can be more comfortably written in C#, but the web application that represents the presentation layer can be faster written in PHP.
  • Development of non-web applications in PHP - If PHP is your favorite language, you can use it for developing GUI and other applications thanks to the Phalanger. You can use all libraries that are available in Mono (and you can distribute the application in compiled form). For example you can use the Gtk# library for developing the GUI of your application. You can find the list of the most interesting Mono libraries at the Mono project web-site.

Compilation of PHP applications

Phalanger is based on .NET/Mono platform which means that the compilation will be done in several steps. In the simplest case, the web application will be compiled during the first request, which makes deployment of PHP applications as simple as in case of standard PHP interpreter. If the script is modified later, Phalanger automatically detects the change and recompiles the modified source files. Using the Phalanger you can also compile the application manually and deploy only the compiled files or if you’re working on non-web application, distribute only the compiled binaries. When the application is started using the Mono platform, the following steps occur:

  1. If the source scripts were changed or were not compiled, Phalanger compiles the source scripts to the IL assembly, which will be executed by .NET/Mono.
  2. .NET/Mono platform is loaded and it compiles the IL code to the native code optimized for the current processor architecture.
  3. The application is executed until it reaches some code that couldn’t be compiled earlier (for example the eval function). When the eval function is executed, the generated script is compiled at run-time using these three steps.

Phalanger Hello world

In the first example we will write and compile simple console application that prints the “Hello world” string. It was tested with the latest version of Mono (1.2.1). After downloading and installing mono, you’ll need to get the latest build of Phalanger, which you can download from the CodePlex releases page. Download the binary distribution for Mono (ZIP file) and extract it to folder, where you want to install Phalanger. After extracting the files, you’ll need to register a few assemblies to the global assembly cache (special place where Mono places shared libraries). This can be done using the following commands (executed in the Bin folder):

gacutil -i PhpNetCore.dll
gacutil -i PhpNetCore.IL.dll
gacutil -i PhpNetClassLibrary.dll

Now, let’s start with the programming. First create file called “hello.php” somewhere on your computer with the following contents:

<?
  echo "Hello world!";
?>

Now we need to compile the application, so we can later execute it using the Mono runtime. To compile it we’ll use the command line compiler (phpc), which is part of the Phalanger installation (the following example assumes that path to the phpc.exe is ../Bin):

mono ../Bin/phpc.exe hello.php

If the compilation completed successfully, you should see the bin subdirectory with the compiled application (file “hello.exe”). To execute the application using mono, you can use the following command:

mono bin/hello.exe

PHP and Gtk#

Gkt# Hello World Previous example was very simple and used only standard PHP libraries. In the next example we will demonstrate more interesting features of Phalanger and create application that uses native Mono libraries. We will use the gtk-sharp and gnome-sharp, which can be used for creating GTK user interface (because GTK was ported for the Windows platform you can use it for developing GUI for portable applications). If you want to use Mono libraries from PHP, you’ll need to enable a few Phalanger extensions - very important extension is support for namespaces, which are used in all Mono libraries. Implementation of namespaces in Phalanger is based on proposals from the PHP community for the future version of PHP language, so the same namespaces implementation may be added in PHP 6 too.

We will now describe how to create application that you can see on the attached screenshot. Besides from the actual source code, we’ll also need to add configuration file, which tells Phalanger what Mono libraries will be used in the application. Let’s start with the configuration file (the name is important, so we’ll call it app.config):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <configSections>
      <!-- Registration of Phalanger config section -->
      <section name="phpNet" 
         type="PHP.Core.ConfigurationSectionHandler, 
           PhpNetCore, Version=2.0.0.0, Culture=neutral, 
           PublicKeyToken=0a8e8c4c76728c71" />
  </configSections>      
  <phpNet>
    <!-- List of referenced libraries -->
    <classLibrary>
      <add assembly="mscorlib" />
      <add assembly="System, Version=1.0.5000.0, 
        Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <add assembly="gnome-sharp, Version=2.4.0.0, 
        Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
      <add assembly="gtk-sharp, Version=2.4.0.0, 
        Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
    </classLibrary>
    <compiler>
      <!-- Compiler config - enable .NET/Mono extensions -->
      <set name="LanguageFeatures">
        <add value="PhpClr" />
      </set>
    </compiler>
  </phpNet>
</configuration>

Configuration using the app.config files is common feature of all .NET/Mono applications and it is handled by the .NET/Mono framework, so we first need to register section that will contain configuration specific for the Phalanger runtime (the phpNet node). In this section you can configure the list of libraries used by the application and also configure the compilation. In this case we need to enable the PHP language extensions for .NET/Mono interoperability using the PhpClr value. By the way, if you’re interested in the list of all libraries that you currently have installed in the global assembly cache and that you can use with Phalanger, you can use the following command (the documentation for the libraries is available on the internet):

gacutil -l

Once we created the configuration file, we can start working on the Gtk# Hello world application. As already mentioned, the Gtk# library allows us to use the Gtk toolkit in the object oriented way. Because Gtk# is built on top of the well-known Gtk library, you may already know most of the objects. The source for the application looks like this:

<?php
  // Import namespaces with the 
  // required objects (PHP/CLR extension)
  import namespace System; 
  import namespace Gtk;
  import namespace Gnome;
 
  class MyProgram
  {
    // Application entry-point (PHP/CLR extension)
    static function Main()
    {
      // Start the application
      new MyProgram();
    }
 
    // Main application widget
    var $app;
    
    function MyProgram()
    {
      // Program and application initialization
      $program = new Program("MyProgram", 
        "0.0", Modules::$UI, array());
      $this->app = new App("MyProgram", "MyWindow");
      $this->app->SetDefaultSize(400, 300);
      $this->app->Remove($this->app->Child);
 
      // Create button
      $btn = new Button("Click me!");
      $btn->BorderWidth = 20;
      $this->app->Child = $btn;
      
      // Set the event handlers
      $btn->Clicked->Add(new EventHandler
        (array($this, "ButtonClick")));
      $this->app->DeleteEvent->Add(new DeleteEventHandler
        (array($this, "OnAppDelete")));
      
      // Start the application
      $this->app->ShowAll();
      $program->Run();
    }
 
    // User clicked on the button - show dialog window
    function ButtonClick($o, $e)
    {
      $dlg = new MessageDialog($this->app, 
         DialogFlags::DestroyWithParent,
         MessageType::Warning, ButtonsType::Close, 
         "Hello world from PHP Gtk#!");
      $dlg->Run();
      $dlg->Destroy();
    }
    
    // Main window was closed - end the application
    function OnAppDelete($o, $e)
    {
      Application::Quit();
    }
  }
?>

(You can download the complete source in ZIP archive if you want gtk-sharp-demo.zip)

You probably noticed, that the source code contains a few constructs that are not part of standard PHP implementation. First feature that appeared in the source code is the namespaces support, which we mentioned earlier. In the application we’ll need classes from the System, Gtk and Gnome namespaces - the EventHandler class is located in the System namespace, Program and App classes can be found in the Gnome namespace and finally, the Button and MessageDialog classes are from the Gtk namespace. Next PHP language extension that is demonstrated in this application is the application entry point - in standard PHP the code is executed from the beginning of the script, which is more appropriate for web pages, but if you’re writing Mono application it is better to use static method (called Main) as an entry point.

The source code contains one class (MyProgram), that represents the running application In the constructor of the class (function with the same name as the class) we create object that represents the program and main application widget (window). After that, we create the button and add it to the main application widget. Before starting the application we need to set two event handlers - functions that will be called by Gtk# when the main widget is closed and when the user clicks on the button. To create the event handler, we use the EventHandler class that takes array with two items as an argument - the first item is reference to the object representing the application ($this) and the second item is the name of the method to be called (”ButtonClick”). Using these information, Phalanger can call the required method when the event occurs in the Gtk#.

Summary

In this article we mentioned a few interesting possibilities that are available to PHP developers interested in the Mono platform. Thanks to the Phalanger you take the best from PHP language (which is dynamic, very flexible and easy to learn) and the best from the Mono platform, like portability, increasing number of interesting libraries, efficiency and common runtime for multiple languages. Thanks to Mono and Phalanger you can also combine more languages (for example PHP and C#) in one project.

core\phalanger_for_mono_users.txt · Last modified: 2007/01/07 21:25 by tomas
Phalanger