### Install PeachPie .NET Templates Source: https://docs.peachpie.io/get-started Installs the latest PeachPie project templates for .NET. This command downloads the necessary templates to create new PeachPie projects. ```bash dotnet new -i "Peachpie.Templates::*" ``` -------------------------------- ### Create and Run PeachPie Console Application Source: https://docs.peachpie.io/get-started Creates a new PeachPie console application in the current directory and then runs it. The first execution may take longer due to dependency downloads and compilation. ```bash dotnet new console -lang PHP dotnet run ``` -------------------------------- ### Create and Build PeachPie Class Library Source: https://docs.peachpie.io/get-started Creates a new PeachPie class library project and builds it into a .dll file. This library can be referenced by other C# or PHP projects. ```bash dotnet new classlib -lang PHP dotnet build ``` -------------------------------- ### Create and Run PeachPie Web Application Source: https://docs.peachpie.io/get-started Creates a new PeachPie ASP.NET Core web application and runs it. This project type compiles PHP files into a website served by a built-in web server. ```bash dotnet new web -lang PHP dotnet run --project Server ``` -------------------------------- ### Sample PHP File Source: https://docs.peachpie.io/net/hosting/aspnetcore A basic PHP file that outputs 'Hello World!'. This serves as a minimal example for a PHP project. ```php ``` -------------------------------- ### Create PeachPie Console Application in VS Code Source: https://docs.peachpie.io/get-started Creates a new PeachPie console application within an empty folder using Visual Studio Code's terminal. This is the initial step for developing a PeachPie console app in VS Code. ```bash dotnet new console -lang PHP ``` -------------------------------- ### Get or Create Web Context (ASP.NET Core) Source: https://docs.peachpie.io/api/ref/context Retrieves or creates a web context instance from an existing `Microsoft.AspNetCore.Http.HttpContext`. This requires adding a reference to the `Peachpie.AspNetCore.Web` package. ```C# using Peachpie.AspNetCore.Web; // Assuming 'httpContext' is an instance of Microsoft.AspNetCore.Http.HttpContext Peachpie.Runtime.Context context = httpContext.GetOrCreateContext(httpContext); ``` -------------------------------- ### PHP Console App Output Example Source: https://docs.peachpie.io/scenarios/beginner/vs-console-app This snippet demonstrates the expected output when a PHP console application built with PeachPie runs successfully, including the 'Hello World!' message and process exit code. ```text Hello World!\nConsoleApp2.exe (process 14116) exited with code 0.\nPress any key to close this window . . .\n ``` -------------------------------- ### Configure Additional Web Static Assets in Startup.cs Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts This C# code snippet demonstrates how to integrate `UseAdditionalWebStaticAssets` into the ASP.NET Core `Startup` class to enable serving static files from custom locations. It assumes necessary configurations are present in `appsettings.json`. ```csharp namespace BlazorApp.Server { public class Startup { public IConfiguration Configuration { get; } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ... app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseAdditionalWebStaticAssets(Configuration); app.UseRouting(); ... } } } ``` -------------------------------- ### Sample MSBuild Project File for Peachpie Source: https://docs.peachpie.io/php/msbuild An example MSBuild project file (`.msbuildproj`) that configures a Peachpie project. It specifies the Peachpie SDK, output type as a library, targets .NET Standard 2.1, and includes all .php files for compilation. ```xml library netstandard2.1 ``` -------------------------------- ### Add PeachPie NuGet Feed (CLI) Source: https://docs.peachpie.io/download This command adds the PeachPie NuGet feed to your local configuration. Replace '{{PASSWORD}}' with your actual Patreon password. Ensure you have the .NET SDK installed. ```bash dotnet nuget add source https://feed.peachpie.io/v3/index.json -n "peachpie feed" -u PAT -p {{PASSWORD}} ``` -------------------------------- ### Target Development Build of PeachPie in Project File Source: https://docs.peachpie.io/scenarios/intermediate/debugging-peachpie Example of a project file (`.msbuildproj`) configured to target a development build of PeachPie. It sets the Sdk to a versioned development build. ```xml library netstandard2.0 ``` -------------------------------- ### PHP Main Function for Console App Source: https://docs.peachpie.io/scenarios/beginner/vs-console-app Defines the main entry point function for a PeachPie PHP console application. This function, named 'main', is intended to be called when the application starts. ```php infoTag->writeWithTreeBuilder($builder, 0); } public function OnInitialized() : void { parent::OnInitialized(); $this->infoTag = new \Peachpie\Blazor\Tag("p"); $this->infoTag->content[] = new \Peachpie\Blazor\Text("Hello world"); } } ``` -------------------------------- ### Peachpie Blazor SDK Project Configuration (MSBuild) Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts This MSBuild project file configures a Peachpie project for Blazor integration. It specifies the output type as a library, targets .NET 5, and sets ProduceReferenceAssembly to false, which is typical for Peachpie Blazor SDK projects. ```xml library net5.0 false ``` -------------------------------- ### Associate PHP Options with .NET Configuration Delegates in PeachPie Source: https://docs.peachpie.io/api/Libraries-Configuration This code shows how to register standard PHP options (like ini_get, ini_set) with PeachPie, associating them with a delegate that gets or sets values from a registered .NET configuration container. ```csharp StandardPhpOptions.Register("option.name", IniFlags.HasDefaultValue, (IPhpConfigurationService configService, string value) => { // Setter logic here, accessing configurations via configService // Example: configService.GetConfiguration().SomeOption = value; }); StandardPhpOptions.Register("option.name", IniFlags.HasDefaultValue, (IPhpConfigurationService configService) => { // Getter logic here, accessing configurations via configService // Example: return configService.GetConfiguration().SomeOption; }); ``` -------------------------------- ### Using Exposed C# Classes/Interfaces in PHP Source: https://docs.peachpie.io/api/Libraries-Architecture Illustrates the usage of C# classes exposed via PeachPie in PHP code. This example shows how to instantiate a C# class, call its methods, access static fields, and reference class constants and context-specific static fields/constants as they would appear in PHP. ```php (new ArrayIterator())->foo([]); echo ArrayIterator::$StaticField; echo ArrayIterator::$ContextStaticField; echo ArrayIterator::A_CLASS_CONSTANT; echo ArrayIterator::ContextConstant; ``` -------------------------------- ### PHP Generics: Instantiation, Static and Instance Methods Source: https://docs.peachpie.io/net/generics Demonstrates the usage of generic types and methods in PHP with PeachPie. Includes examples for instantiating generic types, calling generic static methods, and invoking generic instance methods. Type arguments must be resolved at compile time and cannot be variables or expressions. ```php ; // calling a generic static method System\Activator::CreateInstance(); // calling a generic instance method $urhoNode->CreateComponent(); // accessing the generic type's members print_r( System\Collections\Generic\Comparer::$Default ); ``` -------------------------------- ### Passing .NET Delegates to PHP Global Variables (C#) Source: https://docs.peachpie.io/net/type-system Provides a C# example of creating a .NET delegate (Func) and assigning it to a PHP global variable within the PeachPie context. This enables PHP code to call the .NET delegate. ```csharp mycontext.Globals["delegate"] = new Func( str => str.IsNormalized() ); ``` -------------------------------- ### Integrate PHP Script Navigation in Blazor using PhpScriptProvider Source: https://docs.peachpie.io/scenarios/blazor/api-reference Shows how to embed the `PhpScriptProvider` component within a Blazor Razor page to handle navigation and execution of PHP scripts. This example configures the provider to run a specific script and defines behavior for navigation and not found states. ```cshtml @page "/php/{*sth}" @using Peachpie.Blazor

Navigating to script

Script not found

@code { [Parameter] public string sth { get; set; } } ``` -------------------------------- ### Configure Blazor Host for PHP (C#) Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts This snippet shows how to add PHP support to a Blazor WebAssembly application's host builder. It requires adding the Peachpie.Blazor NuGet package and referencing a type from the PHP scripts assembly to ensure the assembly is downloaded with the client application. ```csharp using Peachpie.Blazor; public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); // Add PHP builder.AddPhp(new[] { typeof(typeInPHPScripts).Assembly}); await builder.Build().RunAsync(); } ``` -------------------------------- ### Using Exposed C# Global Functions/Constants in PHP Source: https://docs.peachpie.io/api/Libraries-Architecture Demonstrates how to call C# static methods exposed as global functions and access C# constants exposed as global constants in PHP. This example covers calling string manipulation functions, output functions, and echoing various types of constants defined in C#. ```php mystrlen(""); myecho(123); echo MYCONST; echo MYCONST2; echo MYCONST3; echo MYCONST4; ``` -------------------------------- ### Configure Application Startup Object (XML) Source: https://docs.peachpie.io/php/msbuild Specifies the main entry point for the application, which can be a file, a global function, a static class method, or a specific class method. If not set, the first compiled script is used. ```XML exe main.php ``` -------------------------------- ### Access PHP Get Array Source: https://docs.peachpie.io/api/ref/context Provides access to the PHP `$_GET` superglobal array through the `Get` property of the `Context`. This is used for retrieving query string parameters. ```C# using Peachpie.Runtime; // Assuming 'context' is an instance of Peachpie.Runtime.Context Pephe.Runtime.PhpArray getParams = context.Get; string searchTerm = getParams["q"].AsString(); ``` -------------------------------- ### Enable Auto Start Session in PeachPie/PHP Configuration Source: https://docs.peachpie.io/php/session Configures the PeachPie application within ASP.NET Core to automatically start the session on each request. This is done by setting the `Session.AutoStart` option in the `AddPhp` method during service configuration. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddPhp(options => { options.Session.AutoStart = true; }); } ``` -------------------------------- ### Build project to create NuGet package Source: https://docs.peachpie.io/scenarios/beginner/create-nuget This command builds the project, which, if configured with 'GeneratePackageOnBuild', will also create the NuGet package. It should be executed from the command shell within the project's directory. ```bash dotnet build ``` -------------------------------- ### PHP Late Static Binding Example Source: https://docs.peachpie.io/api/Late-Static-Binding Demonstrates the use of Late Static Binding in PHP, where the 'static' keyword correctly refers to the calling class (A or B). ```php new A B::make(); // => new B ?> ``` -------------------------------- ### Build PeachPie Project Source: https://docs.peachpie.io/scenarios/intermediate/debugging-peachpie Builds the PeachPie solution from the command line. This is a prerequisite for creating a development build of PeachPie. ```bash dotnet build ``` -------------------------------- ### Create PHP Library Project File (.msbuildproj) Source: https://docs.peachpie.io/scenarios/beginner/reference-php-project This XML file defines the structure and build process for a PHP library project using the PeachPie .NET SDK. It specifies the output type as a library, the target framework, and includes all PHP files as source code for compilation into a DLL and NuGet package. ```xml library netstandard2.1 true true ``` -------------------------------- ### Get Declared PHP Type Information Source: https://docs.peachpie.io/api/ref/context Retrieves type information for a declared PHP type (class) within the current context. It can optionally trigger an autoload process if the type is not immediately found. ```C# using Peachpie.Runtime; // Assuming 'context' is an instance of Peachpie.Runtime.Context Pephe.Runtime.PhpTypeInfo typeInfo = context.GetDeclaredType("MyPhpClass"); if (typeInfo != null) { // Use typeInfo for reflection or other operations } ``` -------------------------------- ### Create default NuGet package Source: https://docs.peachpie.io/scenarios/beginner/create-nuget This command creates a default NuGet package (.nupkg) containing the compiled assembly. It should be run within the project directory. ```bash dotnet pack ``` -------------------------------- ### Create Console CLI Context Source: https://docs.peachpie.io/api/ref/context Creates a new CLI context with output redirected to the application's console. It also initializes `$_SERVER` variables based on the provided main entry point argument. ```C# string[] mainArgs = {"arg1", "arg2"}; Peachpie.Runtime.Context context = Peachpie.Runtime.Context.CreateConsole(mainArgs); ``` -------------------------------- ### Retrieve All Declared Types in Context Source: https://docs.peachpie.io/api/ref/phptypeinfo Shows how to get a list of all PHP types declared within the current runtime context using the Context.GetDeclaredTypes() method. This is useful for discovering available types at runtime. ```csharp using Peachpie.Runtime; using Peachpie.Runtime.Reflection; // Assuming 'context' is an instance of Peachpie.Runtime.Context Context context = ...; var declaredTypes = context.GetDeclaredTypes(); foreach (var typeInfo in declaredTypes) { Console.WriteLine($"Declared Type: {typeInfo.Name}"); } ``` -------------------------------- ### Configure ASP.NET Handler for PHP Files Source: https://docs.peachpie.io/scenarios/beginner/full-net-framework Modifies the web.config file to direct requests for *.php files to the Peachpie request handler. This setup is for IIS 7, IIS Express, or Apache with mod_mono. ```xml ``` -------------------------------- ### PeachPie Project Configuration for Executable Source: https://docs.peachpie.io/scenarios/intermediate/self-contained-exe A .NET project file configured to use the PeachPie SDK, specify an executable output type, set the target framework, define the startup object, and include all PHP files for compilation. ```xml exe net6.0 main.php ``` -------------------------------- ### Enable automatic NuGet packaging on build Source: https://docs.peachpie.io/scenarios/beginner/create-nuget These properties should be inserted into the project file to enable automatic NuGet package creation after a successful build. This simplifies the packaging process by integrating it into the standard build workflow. ```xml true ``` -------------------------------- ### PhpValue Operators in C# Source: https://docs.peachpie.io/api/ref/phpvalue Shows examples of using arithmetic and comparison operators defined for PhpValue, which align with PHP's operator semantics. This includes equality checks, comparisons, bitwise operations, arithmetic, and array-like access. ```csharp // Equality and Comparison var isEqual = val1 == val2; // non-string equality var isNotEqual = val1 != val2; // non-strict inequality var isLess = val1 < val2; var isStrictEqual = val1.StrictEquals(val2); // PHP's === // Bitwise Operations var bitwiseNot = ~val1; var bitwiseAnd = val1 & val2; var bitwiseOr = val1 | val2; var bitwiseXor = val1 ^ val2; // Arithmetic Operations var divisionResult = val1 / val2; // operands converted to number var multiplicationResult = val1 * val2; // operands converted to number // Array-like Access and Conversion var item = val1[1]; var arrayResult = val1.ToArray(); // conversion to array according to PHP semantic var asArray = val1.AsArray(); // gets underlying PhpArray or null var asCallable = val1.AsCallable(); // gets IPhpCallable from PHP' callable ``` -------------------------------- ### Create PHP Library Project (.NET SDK) Source: https://docs.peachpie.io/net/hosting/aspnetcore Defines a PHP project to be compiled as a library. It uses the Peachpie .NET SDK, targets a netstandard framework, and includes all PHP files as source and other files as content, excluding specific directories. ```xml library netstandard2.1 ``` -------------------------------- ### Set Startup Object in Project File (XML) Source: https://docs.peachpie.io/scenarios/beginner/vs-console-app This code snippet shows how to configure the startup object for a PeachPie console application within its project file. It demonstrates changing the default 'program.php' to a custom function named 'main'. ```xml program.php ``` ```xml main ``` -------------------------------- ### Render Static Image File in PHP Script Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts Shows how to render a static image file within a PHP script in a Blazor application. Assumes the image is located in the wwwroot folder, accessible via its relative path. ```php ``` -------------------------------- ### PHP Hello World Script Source: https://docs.peachpie.io/scenarios/intermediate/self-contained-exe A basic PHP script that outputs 'Hello world!' to the console. This serves as the entry point for a self-contained executable. ```php id); ``` -------------------------------- ### Configure PHP Script Router in Blazor WebAssembly Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts Sets up the PhpScriptProvider as a root component in a Blazor WebAssembly application to handle all navigation events. It involves adding PHP support using builder.AddPhp and adding the provider to the root components. ```csharp public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); // Add PHP builder.AddPhp(new[] { typeof(force).Assembly }); // Set the provider as a root component builder.RootComponents.Add(typeof(PhpScriptProvider), "#app"); await builder.Build().RunAsync(); } ``` -------------------------------- ### Include image content files in NuGet package Source: https://docs.peachpie.io/scenarios/beginner/create-nuget This item group specifies that all JPG and PNG files within the project directory and its subdirectories should be included as content in the NuGet package. This is common for including assets like images. ```xml ``` -------------------------------- ### Navigate PHP Scripts with PhpScriptProvider in Blazor Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts Configures Blazor to navigate PHP scripts by setting the Type parameter of PhpScriptProvider to PhpScriptProviderType.Provider. This allows matching URLs with script paths for navigation. Includes Navigating and NotFound template placeholders. ```razor @page "/folder1/{*sth}" @using Peachpie.Blazor

Navigating

Script not found

@code { [Parameter] public string sth { get; set; } } ``` -------------------------------- ### Create and Initialize PhpArray (C#) Source: https://docs.peachpie.io/api/ref/phparray Demonstrates how to create a new PhpArray instance and initialize it with key-value pairs. This includes nested arrays and various data types. ```csharp var phparray = new PhpArray(5) { {"value", true}, {"point", new PhpArray { {"x", 1 }, {"y", 2} } }, {"name", "John Smith"}, {"weight", 168.5}, {"dob", "10/12/1991"}, }; ``` -------------------------------- ### Add PHP Library Reference to ASP.NET Core App (.csproj) Source: https://docs.peachpie.io/net/hosting/aspnetcore Modifies the .csproj file of an ASP.NET Core application to include a reference to a PHP library project and the Peachpie.AspNetCore.Web package. ```xml ``` -------------------------------- ### Create NuGet Package on Build (XML) Source: https://docs.peachpie.io/php/msbuild Configures the build system to automatically create a NuGet package (.nupkg) during the build process. Requires setting a version prefix and enabling package generation. ```XML 1.2.3 true ``` -------------------------------- ### Configure ASP.NET Core Pipeline for PHP Fallback (C#) Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts This C# code configures the ASP.NET Core pipeline to redirect fallback requests, specifically those ending in '.php', to 'index.html'. This ensures that PHP file requests are handled correctly by the Blazor application. ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ... app.UseEndpoints(endpoints => { endpoints.MapFallbackToFile("index.html"); endpoints.MapFallbackToFile("/{**.php}", "index.html"); }); } ``` -------------------------------- ### PHP Session Usage with PeachPie Source: https://docs.peachpie.io/php/session Demonstrates basic session usage in a PHP script running within a PeachPie application. It starts a session, increments a counter stored in $_SESSION, and then closes the session. This requires session state to be configured in the underlying ASP.NET Core application. ```php ``` -------------------------------- ### Sign Assembly with Strong Name (XML) Source: https://docs.peachpie.io/php/msbuild Enables signing the compiled assembly with a strong name using a private key to provide a unique identity. Requires specifying the path to the private key file and enabling assembly signing. ```XML my-key.snk true ``` -------------------------------- ### Visitor Pattern Implementation for PhpValue in C# Source: https://docs.peachpie.io/api/ref/phpvalue Provides a C# example of using the visitor pattern with PhpValue. This pattern allows traversal of the underlying value structure, which is particularly useful for nested arrays and objects, and for implementing serializers. Note the potential for infinite recursion if cycles exist. ```csharp class MyVisitor : PhpVariableVisitor { public override void AcceptNull() { // Handle NULL values } // Override other Accept methods for different types (e.g., AcceptString, AcceptArray) } // Assuming 'value' is an instance of PhpValue value.Accept( new MyVisitor() ); // Traverses through the value, arrays and objects ``` -------------------------------- ### Target .NET Standard 2.0 for Library Projects Source: https://docs.peachpie.io/scenarios/beginner/full-net-framework Sets the project to target .NET Standard 2.0, maximizing compatibility with other .NET projects. This is the recommended approach when compiling a library. ```xml netstandard2.0 ``` -------------------------------- ### Insert PHP Script in Razor Page (Razor/C#) Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts This Razor component demonstrates how to use the PhpScriptProvider to execute and render a specific PHP script ('index.php'). It includes placeholders for 'Navigating' and 'NotFound' states, allowing for custom UI feedback during script loading or if the script is not found. ```razor @page "/index.php" @using Peachpie.Blazor

Navigating

Script not found

``` -------------------------------- ### Add Peachpie.AspNetCore.Mvc NuGet Package Source: https://docs.peachpie.io/scenarios/intermediate/razor Adds the Peachpie.AspNetCore.Mvc NuGet package as a dependency. This package provides the necessary extensions for integrating PHP with ASP.NET Core MVC. ```xml ``` -------------------------------- ### PHP Application Including and Using PHP Library Source: https://docs.peachpie.io/scenarios/beginner/reference-php-project This code illustrates how a PHP application can include and utilize a PHP library class. It uses `require_once` to include the library file and then instantiates `Library\Class1` to call the `encode` method, echoing the result. This approach is common when the library is part of another PHP project. ```php encode('Hello World!'); ?> ``` -------------------------------- ### VS Code Debugger Configuration for PeachPie Source: https://docs.peachpie.io/scenarios/intermediate/debugging-peachpie Configuration for VS Code's `launch.json` to enable debugging of PeachPie. It disables 'Just My Code' and specifies search paths for debug symbols. ```json "justMyCode": false, "symbolOptions": { "searchPaths":["C:\\peachpie\\src\\Peachpie.App\\bin\\Debug\\netstandard2.0"] } ``` -------------------------------- ### Link Static Files from Another Project in Blazor Source: https://docs.peachpie.io/scenarios/blazor/inserting-php-scripts Configures the Blazor project's .csproj file to link static files from another project's wwwroot folder. Uses the 'None' item type with 'Link' and 'CopyToOutputDirectory' properties to include files while maintaining project structure. ```xml ... wwwroot\%(RecursiveDir)/%(FileName)%(Extension) PreserveNewest ... ``` -------------------------------- ### C# Application Calling PHP Library Method Source: https://docs.peachpie.io/scenarios/beginner/reference-php-project This snippet demonstrates how to instantiate a PHP class and call its methods from a C# application after referencing the PHP library. It highlights the use of `Library.Class1` and its `encode` method, with Console output for the result. Implicit type conversions between PHP and C# are managed by the library. ```csharp static void Main(string[] args) { // instantiate PHP class var class1 = new Library.Class1(); // call PHP method with an argument string encoded = class1.encode("Hello World!"); // output the result Console.WriteLine(encoded); } ``` -------------------------------- ### Call PHP Function from JavaScript Source: https://docs.peachpie.io/scenarios/blazor/php-js-interoperability This example demonstrates calling a PHP function from JavaScript. A button click triggers the `window.php.callPHP` method, which sends the function name and parameters (as a JSON structure) to the PHP environment. The PHP function `CallPHP` then decodes the JSON and processes the data. This requires an instance of `PhpScriptProvider` or `PhpComponent` to be available. ```html+php

Click and look at console output

name . " " . $json->surname . " from PHP\n"; } ?> ``` -------------------------------- ### Create Empty CLI Context Source: https://docs.peachpie.io/api/ref/context Creates a new Command Line Interface (CLI) context without a specified output stream. It's crucial to set the WorkingDirectory and RootPath properties after creation for proper script resolution. ```C# Peachpie.Runtime.Context context = Peachpie.Runtime.Context.CreateEmpty(); context.WorkingDirectory = "/path/to/working/dir"; context.RootPath = "/path/to/root"; ```