Use Phalanger integrated PHP and

By Ray Stone,2015-04-05 14:07
23 views 0
Use Phalanger integrated PHP and

    Use Phalanger integrated PHP

    English text:Integrating PHP with .NET Using Phalanger

    Author: Tomas Petricek translator:Hou Bowei

    Phalanger is a PHP language compiler, as well as for PHP runtime.It can be used to compile PHP web project into the. NET bytecode, and used in Windows IIS or on Linux using Mono and Apache as ASP.NET applications to perform.Phalanger, however, is not only compile existing PHP application to the NET.

    We can use the Phalanger create composite and PHP solution, adopted by way of using standard PHP interpreter is impossible.With Phalanger extension, PHP program can be used directly. classes, and application (written in c #, for example) can also be dynamically invoke a PHP script, or use in PHP implementation of functions and classes .

    In this article, I will briefly introduce Phalanger, then look at three types of use.We will discuss how to integrate PHP applications and the NET;How to efficiently run on Windows PHP applications, as well as how to use PHP as ASP.NET view engines (view engine).

    Phalanger profile

    Phalanger has existed for some time.Phalanger is the first edition in 2003, Charles university in Prague, created as a software project.Later began the development of version 2.0, and in 2006 in CodePlex released as open source projects.Microsoft support this project for a period of time, then a Phalanger developers joined Microsoft, and work in the aspects of the dynamic language runtime.

    Phalanger related activities in 2008, thanks to have cooperation with Jadu, it USES the Phalanger is constructed in PHP development of CMS. version.Since 2010, Phalanger development mainly funded by DEVSENSE, it also provides business support for Phalanger.Recently released version 2.1 Phalanger , which improved the compatibility

    with standard PHP implementation, in the process of the realization of dynamic operations using the DLR, and provides the PHP and language (like c #, #, and Visual Basic) interoperability between.

    The Phalanger components

    Phalanger includes multiple independent components, which can be used to develop operation in the PHP applications, and using or Mono to run them:

    ; The Phalanger compiler

    Phalanger will compile PHP source code into assemblies, it can use JIT (Just - in -

    time compiler, it will generate native code for the current platform).The compiled PHP code will

    use Phalanger runtime and dynamic language runtime, thus providing the dynamic characteristics

    of high efficiency of the PHP language.

    ; The Phalanger runtime and the class library

    Phalanger provides an array such as PHP feature implementation.Phalanger also includes for the

    I/O, regular expressions, and other standard PHP class library. implementation. ; Native extensions

    In a 32-bit Windows platforms, Phalanger can be used by local bridging program all existing PHP

    4 extension.Although it brings some runtime overhead, but we don't need extra work can run some

    PHP applications.

    ; The expansion of the host

    By packing provide similar functionality in PHP extensions can be reimplemented.. These

    extensions can be from language, and provide good performance.Phalanger include

    multiple extension, including the SPL, JSON, SimpleXML, MySQL, and MS SQL

    provider.DEVSENSE also provides additional extensions, like Memcached, images and

    cURL, etc.

    ; Integrated with Visual Studio

    Phalanger also integrated with Visual Studio (recently updated support for Visual Studio

    2010).Integration functionality added to the color of the PHP file highlighted and function of smart

    tips, let us can use Phalanger run PHP application debugging.

    Phalanger use cases

    Phalanger largely compatible with PHP 5, you can run a lot of open source PHP project,

    including the WordPress and MediaWiki.We can use it. These programs are integrated into ecosystem, also can develop new project, it will both PHP and the advantage of the

    NET.In the remainder of this article, we will discuss the following three use cases: ; Plan 1: run efficiently PHP applications.Using PHalanger on Windows to compile PHP application

    performance, than by FastCGI using standard PHP interpreter to run high.This makes the choice

    Phalanger deployment of PHP is very attractive in the Windows environment.

    ; Scheme 2: to integrate WordPress and ASP.NET.Use all of the PHP code to call Phalanger

    compiler. libraries.This can be used in PHP and ASP.NET application databases or other

    data Shared between users.

    ; Solution 3: from the ASP.NET application invokes the PHP.The flexibility of the PHP to write a

    script or write the performance of the web application layer is very useful.With Phalanger, we can

    in application development, and using PHP as a scripting language or view engine. The following three sections will discuss in detail the various options.We will first give

    an overview, then look at some technical details, it will show the Phalanger that interest you. Plan 1: run efficiently PHP applications

    Phalanger can efficiently run PHP applications, because of two reasons.At first, it will

    compile PHP source code, rather than explain it;Secondly, it will be the application as

    ASP.NET application is running, it will provide additional performance advantage in Windows.

    Using the Phalanger and compile PHP

    The build process is shown in figure 1.As shown by the graph, the Phalanger will compile PHP source code into the. NET IL (intermediate language), that is architecturally independent junior bytecode.Compiled code will use PHP core library (part of the Phalanger) and the dynamic language runtime (DLR) to perform the standard PHP operation.When the applicationstarts, JIT (just - in - time), the compiler will convert these components to in view of the current processor architecture optimized native code.

    Figure 1. Use Phalanger compile PHP source code to native code process

     as Phalanger evaluation shows that using the Phalanger compiler WordPress under Windows performance is better than by FashCGI using standard PHP parser, is also a little better than by WinCache using PHP.The latest version of the evaluation, however, no test Phalanger, it USES the DLR for further optimization.

    Use ASP.NET to deploy a PHP application

    Phalanger application works in exactly the same way and the ASP.NET application.This makes it have the important performance advantages, especially under the Windows system, process cost more resources than the thread.

    Figure 2 shows the different alternatives of PHP applications run.

    When using standard CGI mode, the web server willstart a new process for each entry request.Under Windows, the efficiency is not high, it also prevents the share is located in the state of Shared memory, also in the process of hard to cache (in - process caching).When using FashCGI mode, the web server will reuse process, so that it does not need tostart new processes for each request.However, this is not the state of Shared memory, because different processes have different status.

    Figure 2. The use of CGI, FashCGI and Phalanger running PHP

    Phalanger behavior and all ASP.NET applications.Separate called Application Pool (Application Pool) ASP.NET process will handle all incoming requests.We can even in a single process (application pool) configured in multiple PHP applications (such as multiple independent of WordPress instance).In the process, there will be multiple threads, the thread will be reused to deal with a single request.Under Windows, the thread is more lightweight than process, so this solution is more efficient, and will consume less memory.

    To run the application in a single process, we can make further optimization, and USES the other interesting scheme.Phalanger will use, for example, the dynamic language runtime (DLR) for dynamic method invocation.The DLR will use caching mechanism adapted to the time, so after several requests, the DLR will "know" application which method to use, and become faster.It is only in the case of a single request processing in the process of can do it.

    Run all the code in a single process also means that applications can be stored in the memory the global state.It can be used to provide the User with WinCache Cache similar functionality, but there will be no cross-process communication load.

    Scheme 2: to integrate WordPress and ASP.NET

    PHP's advantage is to have a large number of excellent open source CMS (WordPress, Joomla, etc.), the forms application (phpBB and other) and a wiki (Mediawiki and other), many of which have passed the test of Phalanger.

    These applications are usually than platform similar packages provide more features.Development based on the ASP.NET web companies may face the following situations:

    ; It needs to the existing solution to add the ASP.NET wiki, BBS or blog, but only exist in the PHP

    suitable application (for example, and with all the necessary features for free).

    ; Application may be running under the child domain, but it should share the user database.In

    addition, once the user log on to the home page, then he should login to the wiki, BBS and blog at

    the same time.

    ASP.NET applications can use ASP.NET Membership (ASP.NET) members of

    management, it is also used to manage users, roles and functions of the standard

    mechanism.With Phalanger, we can modify the open source PHP project, so as to use the same mechanism.The next section will use WordPress to show how to do this.

    Management plugin for WordPress to realize ASP.NET members

    If you are not interested in the code, you can skip this section, see the third case directly.But we won't see technical details, just to let the PHP call. libraries do a brief overview of the PHP extension.

    We can use the plug-in to easily customize in WordPress admin user.Manage user plugins need to implement a PHP class, there are all kinds of member function.One of the most anticipated function is authentication, it will get a user name and password.It should fill the current user's information, or, when the user does not exist, would put the name set to NULL.

    In order to use ASP.NET members of the management to realize the authentication function, we can use the System. Web. The function of Security namespace.Static methods. The Membership ValidateUser will check whether the password is correct, and the Membership. The GetUser returns the user's basic information.Using Phalanger, we can visit object, as it is a standard PHP object, so to achieve very simple authentication mechanism.Code 1 shows a simplified.

    In the WordPress plugin code 1 realize authentication function function

import namespace System:::Web:::Security;

function authenticate (&$username,$password) {

    global $errors;

// Test whether the password is correct

    if (Membership::ValidateUser ($username,$password)) {

    // Get information about the user and fill $userarray

    $user = Membership::GetUser ($username);

    $userarray[ ' user_login ' ] = $user->UserName;

    $userarray[ ' user_email ' ] = $user->Email;

    $userarray[ ' display_name ' ] = $username;

    $userarray[ ' user_pass ' ] = $password;

    // Loading of roles & profiles omitted for simplicity

// Update or create the user information in WordPress

    if ($id = username_exists ($username)) {

    $userarray[ ' ID ' ] = $id;

    wp_update_user ($userarray);



    wp_insert_user ($userarray);

    } else {

    // Report error if the login failed

    $errors->add ( ' user-rejected ' , ' Log-in failed! ' );

    $username = NULL;



    The code first declares the namespace.This is a non-standard Phalanger extension, it from the reference library. namespaces in imported the function (we can use the web. Config file to reference libraries).In a future version of Phalanger will use PHP 5.3 standard namespace support, but the change is still not fully implemented.

    The rest of the code looks like the standard PHP code.The Membership class, however, is actually the standard of classes.Phalanger the PHP classes and classes treated, so we can use standard syntax to invoke. The NET method.Function ValidateUser and GetUser are static function, so use: : syntax to call.GetUser results is MembershipUser object, which contains various properties, including basic information about the user.We can still use the standard notation to access the object fields (they are implemented as attributes).

    As you can see, we can naturally in PHP using functions.Because the code will be compiled into application, so in the call. libraries will not have any load.The next section shows the integration - from the opposite direction. application invokes the PHP.

    Solution 3: from the ASP.NET application invokes the PHP

    PHP is the main advantage of flexibility and simplicity, which makes it become a great language writing scripts and implement rendering HTML.Some people find that, however, want to achieve large-scale application, then use statically typed languages, like Java or c # - will be easier.Use the Phalanger, we can obtain the advantage of both at the same time.

    This part discussed solution shows a way of combination of ASP.NET and PHP.It is based on advanced ASP.NET MVC (model, view and controller) framework, will be in charge interaction layer and presentation layer, separating the business logic of the application.We can use different language to develop the individual components:

    ; C # model and controller

    Model and the controller will be written in c #.This part of the application will implement the

    business logic, usually it would be easier to write in statically typed languages, especially in the

    case of business logic is very complex.In addition, we can also use the technology to store data,

    such as LINQ to use the Task Parallel Library (the Task Parallel Library) using multithreading to

    achieve high performance computing.

    ; PHP view

    The performance of the application layer will be written in PHP.Here, the simplicity and flexibility

    of the PHP will provide maximum benefit.In addition, this means that the application of this

    section can be less from the development experience of developers to write, because most web

    developers of web designers have some understanding of PHP.

    And in some cases, from calling PHP can be useful in c #.For example, you can be in large PHP as a scripting language used in the c # project.This can be very useful, because PHP is a widely known language.Another case is that when using PHP library in c # - is because of the Phalanger duck typing mechanism, this ability has been greatly simplified, the mechanism can even for invoking document complete PHP code to generate static type c # interface.

    In this paper the rest of the content, we will use PHP to achieve ASP.NET application is discussed in this paper the presentation layer.You can find other solution at the end of the article (like scripting) reference information.

    In c #, and PHP to create model view controller application

    First let's take a look at the use of c # and PHP combination created a simple application.Application of the model and the controller is written using c #, as shown in the code 2.In this case, the model is a simple c # class that it represents the product information.In real situations, the class may be responsible for load data from the database, and may use LINQ to implement.

    Code 2: sample web application (c #) model and controller

public class Product {

    public string ProductName { get ; set }

    public double Price { get ; set }


public class HomeController : Controller {

    public ActionResult Index () {

    ViewData.Model = new Product { ProductName = " John Doe " Price = 99.9 };

    return View ();



    The controller component are implemented through the HomeController class, it will inherit the ASP.NET MVC controller.Class contains an action, only show the index page of the application.When the user access/Home/Index (or root URL) will trigger the action.It will create the model (Product class instance) and pass it to the view components.

    In the standard ASP.NET MVC application, the view components often use ASPX page or use with code written using c # or Visual Basic Razor view.Phalanger allows us to use PHP to achieve view.3 shows the code examples.

    Code 3 sample Web applications (PHP) view

< html >< head >

     < title > Sample view written in PHP </ title >

    </ head >

    < body >

     < h1 > Product Listing using Phalanger </ h1 >

     Product: <? echo $MODEL->ProductName; ?> < br />

     Price: <? echo $MODEL->Price; ?>

    </ body ></ html >

    View will use the following description of the ASP.NET MVC extension to rendering.Extension will execute the code shown in the 3 PHP scripts, and defines the global variable called $MODEL, which will contain the data returned by the controller.In the example above, the $MODEL is the class reference.Phalanger on classes and PHP object treated, so using the echo structure, we can easily display properties of the products.

    Example shows the application of the basic structure, but it is very simple, so don't really show in the presentation layer of the benefits of using PHP can give us:

    ; PHP inherent dynamic characteristics make rendering any data structure is very simple.View is not

    only limited to simple scripts, and you can use any existing PHP library, including the popular

    template engine (templating engines).

    ; View can use the PHP include function realization of multiple file structure, so that you can

    complete control of how to generate the page.

    ; Create a view of developers do not need to know anything about the knowledge of the NET.This

    means that the transformation from PHP for the c #, still support the existing developer skills.

    In order to make you a better understanding of this solution works, in the following sections will explain about the technical details of PHP and c # integration.If you are not interested in the details, you can directly jump to conclusion.

    See the essence through the phenomena

    This section describes methods based on PicoMVC project , it lets we can combine

    the PHP and f #.In order to make the sample more simple, I put the transfer from f to c # code.In PicoMVC PHP integration is the core of a simple function, it will achieve a PHP script file name, and use the Phalanger runtime to run.Functions such as code 4.

    Code 4 from the ASP.NET web application invokes the PHP script

void PhalanagerView ( string fileName, object model, HttpContext current) {

    // Initialize PHP request context and output stream

    using (var rc = RequestContext.Initialize (ApplicationContext.Default, current))

    using (var byteOut = HttpContext.Current.Response.OutputStream)

    using (var uftOut = new StreamWriter (byteOut)) {

    // Current context for evaluating PHP scripts

    var phpContext = ScriptContext.CurrentContext;

    // Redirect PHP output to the HTTP output stream

    phpContext.Output = uftOut;

    phpContext.OutputStream = byteOut;

// Declare global $MODEL variable (if model is set)

    if (model != null )

    Operators.SetVariable (phpContext, null , " MODEL " ,

    ClrObject.WrapDynamic (model));

phpContext.Include (fileName, false );



    PhalangeriView method will get the file name (pointing to a PHP script), for as a model of the data returned. NET objects, and the current HTTP context.It will first initialize the RequestContext, thus Phalanger know that it is in dealing with the script as part of the HTTP request.Then, it will ensure that all PHP script generated output will be directly sent as an HTTP response.When as a script to run PHP output can be redirected to the memory stream,

    which in a different way.Finally, the method statement on the global variable MODEL, and use the Phalanger provided Include method to execute PHP scripts.

    This example is not entirely from c # call PHP guidance, you can be found in the Phalanger blog article more detailed information.However, it should be ok, use the Phalanger from c # call the PHP script is relatively easy.This web programming circumstances discussed in this section will be very useful, but it gives us more options.


    This article briefly introduces the Phalanger - for PHP compiler - as well as several programs, we can use it to solve the important problems in practice.Phalanger project are very active recently, version 2.1 includes a lot of the improvement of the compatibility, using dynamic language runtime (DLR) in order to obtain better performance, and the integration with Visual Studio 2010.

    We saw three schemes can be used in the web development Phalanger.The first solution is to use the Phalanger run under Windows environment without modify the open source PHP project (like WordPress).Using Phalanger compiler applications can run under the ASP.NET, the main chance more lightweight, higher operating efficiency.

    In the second scenario, we looked at the integration in ecosystem in PHP applications.With Phalanger extension, we can be called directly in the PHP code. libraries.For example, it can be used to integrate between ASP.NET applications and WordPress user database.

    A final solution demonstrated a web framework, it using PHP as written in the ASP.NET MVC view of language.In this way, developers can easily provide the application of business functions, and PHP developers can use it directly in the presentation layer.

Report this document

For any questions or suggestions please email