Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Phalanger to create a combination of .NET and PHP

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you how to use Phalanger to create a combination of .NET and PHP, which is concise and easy to understand. I hope you can gain something through the detailed introduction of this article.

Phalanger is a PHP language compiler and is also a PHP runtime for .NET. It can be used to compile PHP web projects into. Net bytecode and execute them using IIS in Windows or Mono and Apache on Linux as ASP.NET applications. However, Phalanger is not just about compiling existing PHP applications into .NET.

We can use Phalanger to create a solution that combines .NET and PHP in a way that is impossible with a standard PHP interpreter. With the Phalanger extension, PHP programs can use .NET classes directly, while .NET programs (such as those written in C #) can call PHP scripts dynamically, or use functions and classes implemented in PHP [6].

I'll briefly introduce Phalanger and then look at three usage scenarios. Discusses how to integrate PHP applications with .NET, how to run PHP applications efficiently on Windows, and how to use PHP as the view engine (view engine) for ASP.NET.

Introduction to Phalanger

Phalanger has been around for some time. The * * version of Phalanger was created as a software project at Charles University in Prague in 2003. Development of version 2.0 began later and was released as an open source project in CodePlex in 2006. Microsoft supported the project for some time, and then a Phalanger developer joined Microsoft to work on dynamic language runtimes.

Phalanger-related activities resumed in 2008, thanks to a partnership with Jadu, which used Phalanger to build a .NET version of CMS developed in PHP. Since 2010, the development of Phalanger has been mainly funded by DEVSENSE, which also provides commercial support for Phalanger. The recently released version Phalanger 2.1 [7] improves compatibility with standard PHP implementations, leverages DLR in the implementation of dynamic operations, and provides interoperability between PHP and other .NET languages such as C #, F#, and Visual Basic.

Components of Phalanger

Phalanger includes several partially independent components that can be used to develop PHP applications running on .NET and to run them using .NET or Mono:

Phalanger compiler

Phalanger compiles the PHP source code into a .NET assembly, which can be executed using the .NET JIT (Just-in-time compiler, which generates native code for the current platform). The compiled PHP code uses the Phalanger runtime and the dynamic language runtime, thus providing an efficient implementation of the dynamic features of the PHP language.

Phalanger Runtime and Class Library

Phalanger provides an implementation of PHP features such as arrays. Phalanger also includes .NET implementations for Istroke O, regular expressions, and other standard PHP class libraries.

Local expansion

On the 32-bit Windows platform, Phalanger can use all existing PHP 4 extensions through a native bridge program. Although this brings some runtime load, it allows us to run some PHP applications without extra work.

Managed extension

PHP extensions can also be reimplemented by wrapping similar functionality provided in .NET. These extensions can be written in any .NET language and provide good performance. Phalanger contains several extensions, including providers for SPL, JSON, SimpleXML, MySQL, and MS SQL. DEVSENSE [9] also provides additional extensions, such as Memcached, images, and cURL.

Integration with Visual Studio

Phalanger is also integrated with Visual Studio (the most recent update supports Visual Studio 2010). The integration feature adds color highlighting and smart prompts for PHP files, allowing us to debug PHP applications running with Phalanger.

Phalanger use case

Phalanger is largely compatible with PHP 5 and can run a large number of open source PHP projects, including WordPress and MediaWiki. We can use it to integrate these projects into the .NET ecosystem, or we can develop new projects that have the advantages of both PHP and .NET. In the rest of this article, we will discuss the following three use cases:

Scenario 1: run PHP applications efficiently. PHP applications compiled on Windows using PHalanger perform better than running using the standard PHP interpreter over FastCGI. This makes it attractive to choose Phalanger to deploy PHP in a Windows environment.

Plan 2: integrate WordPress with ASP.NET. PHP code compiled with Phalanger can call all .NET libraries. This can be used to share user databases or other data between PHP and ASP.NET applications.

Scenario 3: call PHP from the ASP.NET application. The flexibility of PHP is useful for writing scripts or writing the presentation layer of web applications. With Phalanger, we can develop applications in .NET and use PHP as a scripting language or view engine.

The following three sections discuss various options in detail. We will first give you an overview, and then look at some technical details that will explain what is interesting to you in Phalanger.

Solution 1: run PHP applications efficiently

Phalanger can run PHP applications efficiently for two reasons. First, it compiles the PHP source code rather than interpreting it; second, it runs the application as an ASP.NET application, which provides additional performance benefits under Windows.

Compiling PHP using Phalanger and .NET

The compilation process is shown in figure 1. As shown in the figure, Phalanger compiles the PHP source code into .NET IL (intermediate language), which is architecture-independent low-level bytecode. The compiled code uses the PHP core library (part of Phalanger) and the dynamic language runtime (DLR) to perform standard PHP operations. When the application starts, the. NET JIT just-in-time compiler converts these components into native code optimized for the current processor architecture

Figure 1. The process of compiling PHP source code into native code using Phalanger

As the Phalanger review shows [10], WordPress compiled with Phalanger performs better under Windows than using the standard PHP interpreter over FashCGI and slightly better than using PHP over WinCache. However, the review did not test the version of Phalanger, which was further optimized using DLR.

Deploy PHP applications using ASP.NET

Phalanger applications run in exactly the same way as ASP.NET applications. This gives it important performance advantages, especially in Windows systems, where processes consume more resources than threads.

Figure 2 shows the different options for running the PHP application.

When using the standard CGI mode, the web server starts a new process for each incoming request. Under Windows, this is inefficient, it also blocks the state of sharing in shared memory, and it is difficult to in-process caching in-process. When using the FashCGI pattern, the web server reuses the process so that it does not need to start a new process for each request. However, it is still not possible to share the state in memory because different processes have different states.

Figure 2. Run PHP using CGI, FashCGI, and Phalanger

Phalanger behaves the same way as all ASP.NET applications. A separate ASP.NET process called Application Pool (Application Pool) handles all incoming requests. We can even configure multiple PHP applications (like separate instances of multiple WordPress) in a single process (application pool). In a process, there are multiple threads that are reused to handle individual requests. Under Windows, threads are more lightweight than processes, so this solution is more efficient and consumes less memory.

For applications running in a single process, we can further optimize and adopt other interesting scenarios. For example, Phalanger uses the dynamic language Runtime (DLR) to make dynamic method calls. DLR uses a time-appropriate caching mechanism, so after a few requests, DLR "knows" which method the application is using and becomes faster. This is only possible if the request is processed in a single process.

Running all code in a single process also means that the application can store global state in memory. This can be used to implement functions similar to the User Cache provided by WinCache, but without the load caused by cross-process communication.

Plan 2: integrate WordPress and ASP.NET

One advantage of PHP is that it has a large number of excellent open source CMS systems (WordPress, Joomla, etc.), forms applications (phpBB and others) and wiki (Mediawiki and others), many of which have passed Phalanger tests.

These applications usually provide more features than similar packages on the .NET platform. Companies that develop ASP.NET-based web pages may face the following situations:

It needs to add wiki, forums, or blogs to existing ASP.NET solutions, but only suitable applications exist in PHP (for example, free and with all the necessary features).

The application may run under a subdomain, but it should share the user database. In addition, once a user logs in to the home page, he should log in to wiki, forum and blog at the same time.

ASP.NET applications can use ASP.NET 's member management (ASP.NET Membership), which is also used to manage standard mechanisms for users, roles, and functions. With Phalanger, we can modify the open source PHP project to use the same mechanism. The next section demonstrates how to do this using WordPress.

Implement the ASP.NET member management plug-in for WordPress

If you are not interested in the code, you can skip this section and look directly at the third case. However, we won't look at the technical details, but just give a brief overview of the PHP extension that lets PHP call the .NET library.

We can easily customize the way users are managed in WordPress using plug-ins. The plug-in for managing users needs to implement a PHP class with various member functions. One of the most anticipated features is authentication, which gets a user name and password. It should populate the information of the current user, or set the name to NULL when the user does not exist.

To implement authentication using ASP.NET member management in .NET, we can use the functionality in the System.Web.Security namespace. The static method Membership.ValidateUser checks whether the password is correct, while Membership.GetUser returns basic information about the user. With Phalanger, we can access the .NET object as if it were a standard PHP object, which makes it easy to implement the validation mechanism. Code 1 shows the simplified code.

Code 1 A function that implements authentication in the WordPress plug-in

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);} else wp_insert_user ($userarray);} else {/ / Report error if the login failed $errors- > add (' user-rejected', Log-in failed'); $username = NULL;}}

The code first declares important namespaces. This is a non-standard Phalanger extension that imports functionality from the .NET namespace of the referenced library (we can use the web.config file to reference the library). In future releases, Phalanger will use the standard namespaces supported by PHP 5.3, but this change has not been fully implemented.

The rest of the code looks the same as standard PHP code. However, the Membership class is actually a standard .NET class. Phalanger treats PHP classes in the same way as .NET classes, so we can call .NET methods using standard syntax. The functions ValidateUser and GetUser are both static functions, so use the:: syntax to call. The result of GetUser is a .NET MembershipUser object with various properties, including basic information about the user. We can still use standard tokens to access the fields of the object (they are implemented as properties of .NET).

As you can see, we can naturally use .NET functionality in PHP. Because the code will be compiled into a .NET program, there will be no load when calling the .NET library. The next section shows the integration in the opposite direction-- calling PHP from a .NET application.

Scenario 3: call PHP from an ASP.NET application

The main advantage of PHP is its flexibility and simplicity, which makes it a great language for scripting and implementing rendering HTML. However, some people find it easier to use statically typed languages, such as Java or C #, to implement large applications. With Phalanger, we can gain both advantages at the same time.

The scenario discussed in this section demonstrates a way to combine ASP.NET and PHP. Based on the advanced ASP.NET MVC (model, view, controller) framework, it separates the presentation layer, the layer responsible for interaction, and the business logic of the application. We can develop separate components in different languages:

C # model and controller

The model and controller are written in C #. This part of the application implements the business logic, which is usually easier to write in a statically typed language, especially if the business logic is very complex. In addition, we can use technologies such as LINQ to store data, and task parallel libraries (Task Parallel Library) to use multithreading for high-performance computing.

PHP view

The presentation layer of the application is written in PHP. Here, the simplicity and flexibility of PHP will provide benefits. In addition, this means that this part of the application can be written by developers with less development experience, because most web developers' web designers know something about PHP.

There are also situations where calling PHP from C # can be useful. For example, you can use PHP as a scripting language in large C # projects. This is also useful because PHP is a well-known language. Another situation is that when using the PHP library in C #, it is greatly simplified because of Phalanger's duck typing mechanism, which can even generate statically typed C # interfaces for calling well-documented PHP code.

In the rest of this article, we will focus on using PHP to implement the presentation layer of ASP.NET applications. You can find references to other solutions (such as scripting) at the end of the article.

Create a model-view-controller application in C # and PHP

First let's take a look at a simple application created using a combination of C # and PHP. The model and controller of the application are written in C #, as shown in Code 2. In this example, the model is just a simple C # class that represents product information. In the real world, this class may be responsible for loading data from the database and may be implemented using LINQ.

Code 2: model and controller for a sample web application (C #)

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 is implemented through the HomeController class, which inherits the ASP.NET MVC controller. Class contains only one action that displays the index page of the application. This action is triggered when the user accesses / Home/Index (or root URL). It creates the model (an instance of the Product class) and passes it to the view component.

In standard ASP.NET MVC applications, view components are typically implemented using ASPX pages or Razor views with code written in C # or Visual Basic. Phalanger allows us to use PHP to implement the view. Code 3 shows this example.

Code 3 A view of the sample Web application (PHP)

Sample view written in PHP Product Listing using Phalanger Product: Price:

The view is rendered using the ASP.NET MVC extension described below. The extension executes the PHP script shown in code 3 and defines a global variable named $MODEL that contains the data returned by the controller. In the above example, $MODEL is a reference to a standard .NET class. Phalanger treats .NET classes and PHP objects equally, so using the echo structure, we can easily display the properties of the product.

The example shows the basic structure of the application, but it is so simple that it doesn't really show the benefits of using PHP at the presentation level:

The inherent dynamic nature of PHP makes it easy to render data of any structure. Views are not limited to simple scripts, and you can use any existing PHP library, including the popular template engine (templating engines).

Views can use PHP's include function to implement a multi-file structure, so you have complete control over how the page is generated.

The developer who creates the view does not need to know anything about .NET. This means that companies that have transitioned from PHP to C # still support existing developer skills.

To give you a better understanding of how this solution works, the following sections explain the technical details of PHP and C# integration. If you are not interested in the details, you can skip directly to the summary section.

See the essence through the phenomenon

The scenario described in this section is based on the PicoMVC project [4], which allows us to combine PHP and F#. To make the example easier, I converted the code from F# to C#. At the heart of PHP integration in PicoMVC is a simple function that takes the file name of the PHP script and runs it using the Phalanger runtime. The function is shown in code 4.

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

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);}}

The PhalangeriView method gets the file name (pointing to the PHP script), the .NET object that represents the data returned as the model, and the current HTTP context. It initializes the RequestContext first, so that Phalanger knows that it is processing the script that is part of the HTTP request. It then ensures that all output generated by the PHP script is sent directly as a HTTP response. When running PHP as a script, the output can be redirected to the memory stream to be processed differently. The method declares the global variable MODEL and executes the PHP script using the Include method provided by Phalanger.

This example is not exactly a guide to calling PHP from C #, you can find more detailed information in the Phalanger blog article. However, it should show that it is quite easy to call PHP scripts from C # using Phalanger. This can be useful in the case of web programming discussed in this section, but it gives us more options.

A brief introduction to Phalanger-- the PHP compiler for .NET-- and several scenarios that we can use to solve important problems in practice. The Phalanger project has been very active recently, and version 2.1 includes many compatibility improvements, the use of dynamic language Runtime (DLR) for better performance, and integration with Visual Studio 2010.

We looked at three scenarios where Phalanger can be used in web development. The * solution is to use Phalanger to run an unmodified open source PHP project (like WordPress) in a Windows environment. Applications compiled with Phalanger can run under ASP.NET, which is lighter and more efficient.

In the second scenario, we looked at the PHP applications integrated into the .NET ecosystem. With the Phalanger extension, we can call the .NET library directly from the PHP code. For example, this can be used to integrate user databases between ASP.NET applications and WordPress.

* one scenario demonstrates a web framework that uses PHP as the language for writing views in ASP.NET MVC. In this way,. NET developers can easily provide the business functions of the application, while PHP developers can use it directly in the presentation layer.

The above is how to use Phalanger to create a combination of .NET and PHP. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 288

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report