Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

PHPER is the framework that allows us to write PHP extensions using pure and safe Rust whenever possible.

PHPER means PHP Enjoy Rust.

Rust ❤️ PHP

The crates are not only the PHP binding for Rust, but also the framework for writing PHP extension.

Purpose

I used to use the C language to write PHP extensions. At that time, C and C++ were the only ways to write PHP extensions.

But I found the problem was that using the C language could easily cause memory problems, which were very troublesome when debugging PHP extensions.

Moreover, third-party libraries in the C language are not easy to use, and version compatibility problems are often encountered in dynamic linking, which is inconvenient to use.

Later, Rust appeared, and I started to use C to call Rust’s FFI to develop PHP extensions. The experience was better than using only the C language.

However, it was not convenient for Rust to generate C ABI and then call C, so I got the idea of using pure Rust to write PHP extensions.

So I started building the framework for phper.

Another goal is to enable PHP to benefit from the Rust ecosystem.

Quick start

At the beginning, you need to:

  1. Be familiar with the Rust language.
  2. Know the general process of PHP extension development.

Here the tutorial will not explain the installation methods of Rust and PHP.

Write your first extension

Here we will write the hello world extension, which has a function, receive the person name and echo hello to the person.

Full example is https://github.com/phper-framework/phper/tree/master/examples/hello.

Steps

  1. Make sure libclang is installed (required by bindgen).

    phper require libclang 9.0+.

    # If you are using debian like linux system:
    sudo apt install llvm-dev libclang-dev
    
  2. Create the cargo project, with the extension name.

    cargo new --lib hello
    
    cd hello
    
  3. Add the metadata to the Cargo.toml to build the .so file.

    # Cargo.toml
    
    [lib]
    crate-type = ["cdylib"]
    

    Run the command to add phper dependency.

    cargo add phper
    
  4. Create the build.rs (adapting MacOS).

    fn main() {
       #[cfg(target_os = "macos")]
       {
          println!("cargo:rustc-link-arg=-undefined");
          println!("cargo:rustc-link-arg=dynamic_lookup");
       }
    }
  5. Add this code to src/lib.rs.

    use phper::{echo, functions::Argument, modules::Module, php_get_module, values::ZVal};
    
    /// The php function, receive arguments with type `ZVal`.
    fn say_hello(arguments: &mut [ZVal]) -> phper::Result<()> {
        // Get the first argument, expect the type `ZStr`, and convert to Rust utf-8
        // str.
        let name = arguments[0].expect_z_str()?.to_str()?;
    
        // Macro which do php internal `echo`.
        echo!("Hello, {}!\n", name);
    
        Ok(())
    }
    
    /// This is the entry of php extension, the attribute macro `php_get_module`
    /// will generate the `extern "C" fn`.
    #[php_get_module]
    pub fn get_module() -> Module {
        // New `Module` with extension info.
        let mut module = Module::new(
            env!("CARGO_PKG_NAME"),
            env!("CARGO_PKG_VERSION"),
            env!("CARGO_PKG_AUTHORS"),
        );
    
        // Register function `say_hello`, with one argument `name`.
        module.add_function("say_hello", say_hello).argument(Argument::new("name"));
    
        module
    }
  6. Build, if your PHP isn’t installed globally, you should specify the path of php-config.

    # Optional, specify if php isn't installed globally,
    # this environment is used by `phper-sys`.
    #
    # export PHP_CONFIG=<Your path of php-config>
    
    # Build libhello.so.
    cargo build
    
  7. Run the php command with the extension.

    php -d "extension=target/debug/libhello.so" -r "say_hello('Bob');"
    

    Then you can get the output:

    Hello, Bob!
    

Write a simple http client

Here we will use Rust crate reqwest to write a simple HTTP client, like curl, but object-oriented.

Full example is at https://github.com/phper-framework/phper/tree/master/examples/http-client.

Imagine that our PHP API should look like this:

<?php

/*** http-client.php ***/

use HttpClient\HttpClientBuilder;
use HttpClient\HttpClient;
use HttpClient\HttpClientException;

$client = (new HttpClientBuilder())
    ->timeout(15000)
    ->cookie_store(true)
    ->build();

$response = $client->get("https://httpbin.org/ip")->send();
var_dump([
    "status" => $response->status(),
    "headers" => $response->headers(),
    "body" => $response->body(),
]);

Here, the namespace of API is HttpClient.

And there are three classes:

  • HttpClientBuilder is the builder of HttpClient.
  • HttpClient will send a http request and generate a http response.
  • HttpClientException will be throw when http request failed.

Steps

Before writing the code, we first prepare the dependency and startup code.

  1. Make sure libclang is installed (required by bindgen).

    phper require libclang 9.0+.

    # If you are using debian like linux system:
    sudo apt install llvm-dev libclang-dev
    
  2. Create the cargo project, with the extension name.

    cargo new --lib http-client
    
    cd http-client
    
  3. Add the metadata to the Cargo.toml to build the .so file.

    [lib]
    crate-type = ["cdylib"]
    

    Run the command to add dependencies.

    cargo add phper
    cargo add reqwest --features blocking --features cookies
    cargo add thiserror
    
  4. Create the build.rs (adapting MacOS).

    fn main() {
       #[cfg(target_os = "macos")]
       {
          println!("cargo:rustc-link-arg=-undefined");
          println!("cargo:rustc-link-arg=dynamic_lookup");
       }
    }

Now let’s begin to finish the logic.

  1. First, we create src/errors.rs to make the HttpClientException class:

    use phper::{
        classes::{ClassEntry, ClassEntity, StateClass},
        errors::{exception_class, Throwable},
    };
    
    /// The exception class name of extension.
    const EXCEPTION_CLASS_NAME: &str = "HttpClient\\HttpClientException";
    
    pub fn make_exception_class() -> ClassEntity<()> {
        let mut class = ClassEntity::new(EXCEPTION_CLASS_NAME);
        // The `extends` is same as the PHP class `extends`.
        class.extends(StateClass::from_name("Exception"));
        class
    }
    
    #[derive(Debug, thiserror::Error)]
    pub enum HttpClientError {
        #[error(transparent)]
        Reqwest(reqwest::Error),
    
        #[error("should call '{method_name}()' before call 'body()'")]
        ResponseAfterRead { method_name: String },
    
        #[error("should not call 'body()' multi time")]
        ResponseHadRead,
    }
    
    impl Throwable for HttpClientError {
        fn get_class(&self) -> &ClassEntry {
            ClassEntry::from_globals(EXCEPTION_CLASS_NAME).unwrap_or_else(|_| exception_class())
        }
    }
    
    impl From<HttpClientError> for phper::Error {
        fn from(e: HttpClientError) -> Self {
            phper::Error::throw(e)
        }
    }
    

    The make_*_class functions is for registering class in src/lib.rs later.

    The ClassEntity represents the class entry hold the state as generic type, so you can wrap the Rust struct as state in PHP class, which is the common usage of class in php extensions (if using C/C++ to develop PHP extension, the PHP class commonly wrap the C/C++ pointer).

    But here the HttpClientException hasn’t state required, so the class in ClassEntity<()>.

  2. Then, create the HttpClientBuilder class in src/client.rs.

    use phper::{
        classes::{ClassEntry, ClassEntity},
        errors::{exception_class, Throwable},
    };
    
    /// The exception class name of extension.
    const EXCEPTION_CLASS_NAME: &str = "HttpClient\\HttpClientException";
    
    pub fn make_exception_class() -> ClassEntity<()> {
        let mut class = ClassEntity::new(EXCEPTION_CLASS_NAME);
        // The `extends` is same as the PHP class `extends`.
        class.extends(StateClass::from_name("Exception"));
        class
    }
    
    #[derive(Debug, thiserror::Error)]
    pub enum HttpClientError {
        #[error(transparent)]
        Reqwest(reqwest::Error),
    
        #[error("should call '{method_name}()' before call 'body()'")]
        ResponseAfterRead { method_name: String },
    
        #[error("should not call 'body()' multi time")]
        ResponseHadRead,
    }
    
    impl Throwable for HttpClientError {
        fn get_class(&self) -> &ClassEntry {
            ClassEntry::from_globals(EXCEPTION_CLASS_NAME).unwrap_or_else(|_| exception_class())
        }
    }
    
    impl From<HttpClientError> for phper::Error {
        fn from(e: HttpClientError) -> Self {
            phper::Error::throw(e)
        }
    }
    
    use phper::{
        alloc::ToRefOwned,
        classes::{StateClass, Visibility},
        functions::Argument,
    };
    use reqwest::blocking::{Client, ClientBuilder};
    use std::{mem::take, time::Duration};
    
    const HTTP_CLIENT_BUILDER_CLASS_NAME: &str = "HttpClient\\HttpClientBuilder";
    
    const HTTP_CLIENT_CLASS_NAME: &str = "HttpClient\\HttpClient";
    
    pub type ClientClass = StateClass<Option<Client>>;
    
    pub fn make_client_builder_class(client_class: ClientClass) -> ClassEntity<ClientBuilder> {
        // `new_with_default_state_constructor` means initialize the state of `ClientBuilder` as
        // `Default::default`.
        let mut class = ClassEntity::new_with_default_state_constructor(HTTP_CLIENT_BUILDER_CLASS_NAME);
    
        // Inner call the `ClientBuilder::timeout`.
        class
            .add_method("timeout", Visibility::Public, |this, arguments| {
                let ms = arguments[0].expect_long()?;
                let state = this.as_mut_state();
                let builder: ClientBuilder = take(state);
                *state = builder.timeout(Duration::from_millis(ms as u64));
                Ok::<_, phper::Error>(this.to_ref_owned())
            })
            .argument(Argument::new("ms"));
    
        // Inner call the `ClientBuilder::cookie_store`.
        class
            .add_method("cookie_store", Visibility::Public, |this, arguments| {
                let enable = arguments[0].expect_bool()?;
                let state = this.as_mut_state();
                let builder: ClientBuilder = take(state);
                *state = builder.cookie_store(enable);
                Ok::<_, phper::Error>(this.to_ref_owned())
            })
            .argument(Argument::new("enable"));
    
        // Inner call the `ClientBuilder::build`, and wrap the result `Client` in
        // Object.
        class.add_method("build", Visibility::Public, move |this, _arguments| {
            let state = take(this.as_mut_state());
            let client = ClientBuilder::build(state).map_err(HttpClientError::Reqwest)?;
            let mut object = client_class.init_object()?;
            *object.as_mut_state() = Some(client);
            Ok::<_, phper::Error>(object)
        });
    
        class
    }
  3. Follow this method to complete HttpClient, RequestBuilder and Response, see full example for details.

  4. Register all classes in src/lib.rs.

  5. All codes are finished, so we can build the extension .so, and run the PHP script in the beginning of the tutorial with the extension.

    cargo build
    
    php -d "extension=target/debug/libhttp_client.so" http-client.php
    

    Here is the result I got:

    array(3) {
    ["status"]=>
    int(200)
    ["headers"]=>
    array(7) {
        ["date"]=>
        array(1) {
        [0]=>
        string(29) "Sat, 03 Dec 2022 09:15:11 GMT"
        }
        ["content-type"]=>
        array(1) {
        [0]=>
        string(16) "application/json"
        }
        ["content-length"]=>
        array(1) {
        [0]=>
        string(2) "33"
        }
        ["connection"]=>
        array(1) {
        [0]=>
        string(10) "keep-alive"
        }
        ["server"]=>
        array(1) {
        [0]=>
        string(15) "gunicorn/19.9.0"
        }
        ["access-control-allow-origin"]=>
        array(1) {
        [0]=>
        string(1) "*"
        }
        ["access-control-allow-credentials"]=>
        array(1) {
        [0]=>
        string(4) "true"
        }
    }
    ["body"]=>
    string(33) "{
    "origin": "223.104.76.175"
    }
    "
    }
    

Integrate with PECL

As can be seen from the quick start example, using phper to develop a PHP extension doesn’t require the phpize and make processes, as you would when developing with C/C++.

However, if you intend to publish the extension on PECL (the official repository of PHP extensions), you will need to integrate the phper project with phpize and make since the PECL install command will call them.

This chapter will guide you on how to integrate the phper project with pecl and phpize.

Steps

Adapt to phpize

  1. At first, imagine you have finished the hello project follow write your first extension, can build the php extension .so file successfully.

  2. And then, create the config.m4 file using by phpize (In theory, config.w32 is also required for compatibility with Windows, but now phper don’t support Windows).

    PHP_ARG_ENABLE([hello],
      [whether to enable hello support],
      [AS_HELP_STRING([--enable-hello],
        [Enable hello support])],
      [no])
    
    dnl If not enable, `cargo build` run with argument `--release`.
    PHP_ARG_ENABLE([cargo_debug], [whether to enable cargo debug mode],
    [  --enable-cargo-debug           Enable cargo debug], no, no)
    
    if test "$PHP_hello" != "no"; then
      dnl Check cargo command exists or not.
      AC_PATH_PROG(CARGO, cargo, no)
      if ! test -x "$CARGO"; then
        AC_MSG_ERROR([cargo command missing, please reinstall the cargo distribution])
      fi
    
      AC_DEFINE(HAVE_hello, 1, [ Have hello support ])
    
      PHP_NEW_EXTENSION(hello, [ ], $ext_shared)
    
      CARGO_MODE_FLAGS="--release"
      CARGO_MODE_DIR="release"
    
      if test "$PHP_CARGO_DEBUG" != "no"; then
        CARGO_MODE_FLAGS=""
        CARGO_MODE_DIR="debug"
      fi
    
      cat >>Makefile.objects<< EOF
    all: cargo_build
    
    clean: cargo_clean
    
    cargo_build:
        # Build the extension file
    	PHP_CONFIG=$PHP_PHP_CONFIG cargo build $CARGO_MODE_FLAGS
    
        # Copy the extension file from target dir to modules
    	if [[ -f ./target/$CARGO_MODE_DIR/libhello.dylib ]] ; then \\
    		cp ./target/$CARGO_MODE_DIR/libhello.dylib ./modules/hello.so ; fi
    	if [[ -f ./target/$CARGO_MODE_DIR/libhello.so ]] ; then \\
    		cp ./target/$CARGO_MODE_DIR/libhello.so ./modules/hello.so ; fi
    
    cargo_clean:
    	cargo clean
    
    .PHONY: cargo_build cargo_clean
    EOF
    
      dnl Symbolic link the files for `cargo build`
      AC_CONFIG_LINKS([ \
        Cargo.lock:Cargo.lock \
        Cargo.toml:Cargo.toml \
        build.rs:build.rs \
        src:src \
        ])
    fi
    
    

    Here we add the configure option --enable-cargo-debug, whether to enable cargo debug mode.

    I think this isn’t the best way of writing, because I am not very familiar with the syntax of autoconf, but it can work, if you have a better way of writing, welcome to PR. :-)

  3. Don’t forget to add the .gitignore, because phpize and ./configure will generate too much temporary files.

    hello-*.tgz
    *.lo
    *.la
    .libs
    acinclude.m4
    aclocal.m4
    autom4te.cache
    build
    config.guess
    config.h
    config.h.in
    config.h.in~
    config.log
    config.nice
    config.status
    config.sub
    configure
    configure.ac
    configure.in
    include
    install-sh
    libtool
    ltmain.sh
    Makefile
    Makefile.fragments
    Makefile.global
    Makefile.objects
    missing
    mkinstalldirs
    modules
    php_test_results_*.txt
    phpt.*
    run-test-info.php
    run-tests.php
    tests/**/*.diff
    tests/**/*.out
    tests/**/*.exp
    tests/**/*.log
    tests/**/*.db
    tests/**/*.mem
    tmp-php.ini
    

Now phpize is ready to run, let’s try!

phpize
./configure --enable-cargo-debug
make
make install

Alright, the hello extension will be installed in php extension directory.

Adapt to PECL

  1. To integrate with PECL, we have to create the package.xml file.

     <?xml version="1.0"?>
     
     <package version="2.0" 
     	xmlns="http://pear.php.net/dtd/package-2.0" 
     	xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" 
     	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd">
     	<name>hello</name>
     	<channel>pecl.php.net</channel>
     	<summary>Hello world example.</summary>
     	<description>The Hello world example of phper.</description>
     	<lead>
     		<name>jmjoy</name>
     		<user>jmjoy</user>
     		<email>jmjoy@apache.org</email>
     		<active>yes</active>
     	</lead>
     	<date>1970-01-01</date>
     	<version>
     		<release>0.0.0</release>
     		<api>0.0.0</api>
     	</version>
     	<stability>
     		<release>stable</release>
     		<api>stable</api>
     	</stability>
     	<license uri="http://license.coscl.org.cn/MulanPSL2/">MulanPSL-2.0</license>
     	<notes>        Release notes.	</notes>
     	<contents>
     		<dir name="/">
     			<file name="Cargo.lock" role="src" />
     			<file name="Cargo.toml" role="src" />
     			<file name="README.md" role="doc" />
     			<file name="build.rs" role="src" />
     			<file name="config.m4" role="src" />
     			<file name="src/lib.rs" role="src" />
     		</dir>
     	</contents>
     	<dependencies>
     		<required>
     			<php>
     				<min>7.2.0</min>
     			</php>
     			<pearinstaller>
     				<min>1.4.0</min>
     			</pearinstaller>
     		</required>
     	</dependencies>
     	<providesextension>hello</providesextension>
     	<extsrcrelease>
     		<configureoption default="no" name="enable-cargo-debug" prompt="enable cargo debug?" />
     	</extsrcrelease>
     </package>
    

    *The example hello in phper github repository not run pecl well, because it’s the sub crate of phper, not a separate project.

All is OK, try to build the pecl package and install it.

pecl package
pecl install hello-*.tgz

We will receive output like this at the end if the whole is successful.

configuration option "php_ini" is not set to php.ini location
You should add "extension=hello.so" to php.ini

Zval

Refer to: https://www.phpinternalsbook.com/php7/zvals/basic_structure.html#the-zval-struct

A zval (short for “Zend value”) represents an arbitrary PHP value. As such it is likely the most important structure in all of PHP and you’ll be working with it a lot.

The phper::values::ZVal is the wrapper of php zval.

Actual type of ZVal

PHP is a dynamically typed language, zval can represent multiple types, but there is only one type at a time, you can use phper::values::ZVal::get_type_info to get the actual type.

Convert Rust type to ZVal

The phper::values::ZVal implements a lot of std::convert::From for the conversion.

Here is the mapping of relationships between Rust types and base PHP types.

TraitRust typePHP type
From<()>()null
From<bool>boolbool
From<i64>i64long
From<f64>f64double
From<&str>&strstring
From<&CStr>&CStrstring
From<&[u8]>&[u8]string
From<Vec<u8>>Vec<u8>string
From<ZString>phper::strings::ZStringstring
From<ZArray>phper::arrays::ZArrayarray
From<ZObject>phper::objects::ZObjectobject

There are also composite types that implement From.

  • From<Option<T>>: if Some(T), T will be converted to PHP type like From<T>, or None will be converted to null.
use phper::values::ZVal;

assert!(ZVal::from(()).get_type_info().is_null());
assert!(ZVal::from(100i64).get_type_info().is_long());

Convert ZVal to Rust type

Now you can use as_* or expect_* methods to convert ZVal to Rust types.

  • The as_* returns Option<T>.

  • The expect_* returns phper::Result<T>, if convert failed, phper::errors::ExpectTypeError will be returned, with the message: type error: must be of type {expect_type}, {actual_type} given").

use phper::echo;
use phper::values::ZVal;

fn say_hello(arguments: &mut [ZVal]) -> phper::Result<()> {
    // Get the first argument, expect the type `ZStr`, and convert to Rust utf-8
    // str.
    let name = arguments[0].expect_z_str()?.to_str()?;

    // Macro which runs PHP internal function `echo`.
    echo!("Hello, {}!\n", name);

    Ok(())
}

Generic conversion via FromZVal / FromZValMut

Besides calling expect_* directly, you can also use generic conversion traits:

And call phper::values::ZVal::expect_type / phper::values::ZVal::expect_mut_type to perform conversion.

use phper::values::{FromZVal, FromZValMut, ZVal};

fn expect_immutable<'a, T: FromZVal<'a>>(val: &'a ZVal) -> phper::Result<T> {
    val.expect_type()
}

fn expect_mutable<'a, T: FromZValMut<'a>>(val: &'a mut ZVal) -> phper::Result<T> {
    val.expect_mut_type()
}

fn demo() -> phper::Result<()> {
    let z = ZVal::from(123i64);
    let immutable: i64 = expect_immutable(&z)?;
    assert_eq!(immutable, 123);

    let mut z = ZVal::from(456i64);
    let mutable: &mut i64 = expect_mutable(&mut z)?;
    *mutable += 1;
    assert_eq!(z.expect_long()?, 457);

    Ok(())
}

Value copy & reference counting copy

The phper::values::ZVal both implements std::clone::Clone and phper::alloc::RefClone.

  • std::clone::Clone: represent value copy (Type ZObject is excluded because it is always passed by reference).

  • phper::alloc::RefClone: represent reference counting copy (Type (), bool, i64, f64 is excluded because they are not reference counting types).

PHP internal cast

Refer to: https://www.phpinternalsbook.com/php7/zvals/casts_and_operations.html#casts

PHP is a weakly typed language, yet it supports type casting internally.

The zend engine provides convert_to_* functions to do the type cast, and ZVal wraps them directly.

Callable

The phper::values::ZVal can be called via phper::values::ZVal::call. Make sure that the actual type is callable (string, array or closure).

use phper::values::ZVal;
use phper::arrays::ZArray;

let mut arr = ZArray::new();
arr.insert("a", ZVal::from(1));
arr.insert("b", ZVal::from(2));
let ret = ZVal::from("json_encode").call(&mut [ZVal::from(arr)]).unwrap();
assert_eq!(ret.expect_z_str().unwrap().to_str(), Ok(r#"{"a":1,"b":2}"#));

Internal types

DST & Owned Type

In Rust, there are many types that appear in pairs, like str / String, OsStr / OsString, CStr / CString.

For example:

  • str: Dynamically sized type, implements !Sized, usually used with reference notation, as &str.
  • String: Ownership type, encapsulates a pointer to a heap memory allocation.

PHPER follows this design, there are the following types:

It seems that there is no need to separate into two types, but ZStr, ZArr, and ZObj are all transparent types. Therefore, the fields of the struct cannot be changed. Separating an ownership struct ZString, ZArray, and ZObject, and then we can change fields of the struct in the future.

Mapping relationship

Here is the mapping of relationships between Rust types and base PHP types.

Rust typePHP type
()null
boolbool
i64long
f64double
ZStr / ZStringstring
ZArr / ZArrayarray
ZObj / ZObjectobject
ZResresource

Why is there no ZResource? Because Resource is a relatively old type, it is generally replaced by Class now, and the role of ZRes is only compatible with old extension resources.

Z Str

A string is series of characters, where a character is the same as a byte.

Refer: https://www.php.net/manual/en/language.types.string.php

The &ZStr and ZString are wrappers for zend_string.

ZStr can be converted to &[u8], &CStr and &str.

ZString can be constructed from impl AsRef<[u8]> and has pair of from_raw() and into_raw(), like in [Box].

use phper::strings::ZString;

let s = ZString::new("Hello world!");

// Will leak memory.
let ptr = ZString::into_raw(s);

// retake pointer.
let ss = unsafe { ZString::from_raw(ptr) };

// `ZString` implements `PartialEq`.
assert_eq!(ss, "Hello world!");

ZString can be dereferenced to ZStr.

use phper::strings::ZString;

let s = ZString::new("Hello world!");

// `to_str` is the method of `ZStr`.
assert_eq!(s.to_str(), Ok("Hello world!"));

ZStr implements ToOwned. It can upgrade to ZString by value copying.

Because zend_string is reference counting type, so ZStr also implements ToRefOwned (just like RefClone for ZVal), can upgrade to ZString by refcount increment.

use phper::sys;
use phper::strings::ZStr;
use phper::alloc::ToRefOwned;

unsafe extern "C" {
    fn something() -> *mut sys::zend_string;
}

let s = unsafe { ZStr::from_mut_ptr(something()) };

// By value copying.
let _s = s.to_owned();

// By refcount increment.
let _s = s.to_ref_owned();

Note that neither ZStr nor ZString implements Send and Sync, because PHP is single-threaded.

Z Arr

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Refer: https://www.php.net/manual/en/language.types.array.php

In fact, I don’t agree with PHP’s practice of mixing list and map. I prefer python to separate list and dictionary as two types. For example, when serializing into json, the serialization function has to judge whether the key of the array starts from 0 and increment by 1 to confirm whether the array is a list. I think it is a waste of performance.

The &ZArr and ZArray are the wrappers for zend_array (same as Hashtable).

&ZArr acts like HashMap, also has api insert(), get(), remove(), but it’s key type is Key and value type is ZVal.

Notice that phper prefers to use Symtables api zend_symtable_*, so get(42) and get("42") should be considered the same.

ZArray can be dereferenced to ZArr.

use phper::arrays::{ZArray, InsertKey};
use phper::values::ZVal;

let mut arr = ZArray::new();

arr.insert(InsertKey::NextIndex, ZVal::default());
arr.insert(10, ZVal::from(100));
arr.insert("foo", ZVal::from("bar"));

let _i = arr.get("10");

arr.remove("foo");

ZArr can be iterated by iter().

use phper::arrays::ZArray;
use phper::values::ZVal;

let arr = ZArray::new();

for (k, v) in arr.iter() {
}

ZArr implements ToOwned and it can upgrade to ZArray by value copying via zend_array_dup.

Because zend_array is reference counting type, ZArr also implements ToRefOwned (similar to RefClone for ZVal), allowing an upgrade to ZArray by incrementing the refcount.

use phper::sys;
use phper::arrays::ZArr;
use phper::alloc::ToRefOwned;

unsafe extern "C" {
    fn something() -> *mut sys::zend_array;
}

let arr = unsafe { ZArr::from_mut_ptr(something()) };

// By value copy.
let _arr = arr.to_owned(); 

// By refcount increment.
let _arr = arr.to_ref_owned();

Note that neither ZArr nor ZArray implements Send and Sync, because PHP is single-threaded.

Z Obj

The &ZObj and ZObject are the wrappers for zend_object.

You can do OOP operation using ZObj or ZObject, like getting and setting properties, calling methods, etc.

use phper::classes::ClassEntry;
use phper::objects::ZObject;
use phper::errors::exception_class;

let mut e: ZObject = exception_class().new_object([]).unwrap();
e.set_property("code", 403);
e.set_property("message", "oh no");
let _message = e.call("getMessage", []).unwrap();

ZObj implements ToRefOwned to upgrade to ZObject, duplicate the object via increment refcount.

ZObject implements RefClone, same as ZObj::to_owned.

use phper::sys;
use phper::objects::ZObj;
use phper::alloc::ToRefOwned;

unsafe extern "C" {
    fn something() -> *mut sys::zend_object;
}

let o = unsafe { ZObj::from_mut_ptr(something()) };

// By refcount increment.
let _o = o.to_ref_owned();

Note that neither ZObj nor ZObject implements Send and Sync, because PHP is single-threaded.

Module

Just to clarify, in PHP’s source code, PHP extensions are named as “PHP modules.”

PHP extensions (aka PHP “modules”) are loaded in INI files with an “extension=pib.so” line.

Refer: https://www.phpinternalsbook.com/php7/extensions_design/zend_extensions.html#on-differences-between-php-and-zend-extensions

Module is the entry of registering hooks, functions, classes, ini properties, constants, etc.

Hooks

PHP is a complex piece of machinery, and its lifecycle should be understood by anyone who wants to grasp how PHP operates.

Refer: https://www.phpinternalsbook.com/php7/extensions_design/php_lifecycle.html

PHP provides many hooks in lifecycle for extension to override.

There are MINIT, MSHUTDOWN, RINIT, RSHUTDOWN, GINIT, RSHUTDOWN.

Correspondingly, PHPER sets these hooks to complete some internal operations, such as registering extension information, functions, classes, constants, etc. However, it also exposes these hooks to users for overwriting.

The following presents the corresponding relationships between PHP hooks and Module methods:

PHP hooksModule method
MINITon_module_init
MSHUTDOWNon_module_shutdown
RINITon_request_init
RSHUTDOWNon_request_shutdown
use phper::{modules::Module, php_get_module};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.on_module_init(|| {
        // Do somethings in `MINIT` stage.
    });

    module
}

Register functions

In PHPER, you can use add_function to register functions.

use phper::{modules::Module, php_get_module, functions::Argument, echo};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("say_hello", |arguments| -> phper::Result<()> {
        let name = arguments[0].expect_z_str()?.to_str()?;
        echo!("Hello, {}!\n", name);
        Ok(())
    }).argument(Argument::new("name"));

    module
}

This example registers a function called say_hello and accepts a parameter name passed by value, similarly in PHP:

<?php

function say_hello($name) {
    echo "Hello, {$name}\n";
}

You can get the function info by php --re <EXTENSION_NAME>:

Extension [ <persistent> extension #56 hello version <no_version> ] {

  - Functions {
    Function [ <internal:hello> function say_hello ] {

      - Parameters [1] {
        Parameter #0 [ <required> $name ]
      }
    }
  }
}

It is useful to register the parameters of the function, which can limit the number of parameters of the function.

Especially when the parameters need to be passed by reference.

use phper::{modules::Module, php_get_module, functions::Argument};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("add_count", |arguments| -> phper::Result<()> {
        let count = arguments[0].expect_mut_z_ref()?;
        *count.val_mut().expect_mut_long()? += 100;
        Ok(())
    }).argument(Argument::new("count").by_ref());

    module
}

Here, the argument is registered as Argument::by_ref. Therefore, the type of the count parameter is no longer long, but a reference.

Argument and return type modifiers

An argument is required and untyped unless you say otherwise. The modifiers that change that:

ModifierEffect
optionalthe argument may be omitted
with_default_valuethe default shown by reflection, and used for an argument skipped by name. Implies optional. On PHP 7.x, the same as optional
with_type_hint / allow_nullthe declared type, and whether it accepts null
by_refpass by reference rather than by value

An argument type the running PHP does not have is declared untyped: mixed before PHP 8.0, and iterable on PHP 7.0.

Here we define a function that accepts a nullable class (in this case, an interface), a string with a default value, and an optional bool:

use phper::{modules::Module, php_get_module, functions::Argument, echo};
use phper::types::ArgumentTypeHint;

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("my_function", |_| -> phper::Result<()> {
        Ok(())
    })
    .argument(Argument::new("a_class").with_type_hint(ArgumentTypeHint::ClassEntry(String::from(r"\MyNamespace\MyInterface"))).allow_null())
    .argument(Argument::new("name").with_type_hint(ArgumentTypeHint::String).with_default_value("'my_default'"))
    .argument(Argument::new("optional_bool").with_type_hint(ArgumentTypeHint::Bool).optional());

    module
}

The output of php --re for this function would look like:

    Function [ <internal:integration> function my_function ] {

      - Parameters [3] {
        Parameter #0 [ <required> ?\MyNamespace\MyInterface $a_class ]
        Parameter #1 [ <optional> string $name = 'my_default' ]
        Parameter #2 [ <optional> bool $optional_bool = <default> ]
      }
    }

Declare a union type

ArgumentTypeHint::Union and ReturnTypeHint::Union declare a type such as int|string or Foo|false|null. False is available as a member, or on its own. allow_null on a union adds null, the same as a Null member.

use phper::{modules::Module, php_get_module, functions::{Argument, ReturnType}};
use phper::types::{ArgumentTypeHint, ReturnTypeHint};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("my_function", |_| -> phper::Result<bool> {
        Ok(false)
    })
    .argument(Argument::new("key").with_type_hint(ArgumentTypeHint::Union(vec![
        ArgumentTypeHint::Int,
        ArgumentTypeHint::String,
    ])))
    .argument(Argument::new("parent").with_type_hint(ArgumentTypeHint::Union(vec![
        ArgumentTypeHint::ClassEntry(String::from(r"MyNamespace\MyInterface")),
        ArgumentTypeHint::False,
        ArgumentTypeHint::Null,
    ])).with_default_value("null"))
    .return_type(ReturnType::new(ReturnTypeHint::Union(vec![
        ReturnTypeHint::String,
        ReturnTypeHint::False,
    ])));

    module
}

The output of php --re for this function would look like:

    Function [ <internal:integration> function my_function ] {

      - Parameters [2] {
        Parameter #0 [ <required> string|int $key ]
        Parameter #1 [ <optional> MyNamespace\MyInterface|false|null $parent = null ]
      }
      - Return [ string|false ]
    }

Version notes:

  • Union types and false need PHP 8.0. On PHP 7.x the argument or return is declared untyped.
  • A union of two or more classes needs PHP 8.0.2. Earlier 8.0 releases cannot split the class names.
  • From PHP 8.2, iterable in a union is shown as Traversable|array, as it is in userland.

A union that PHP would reject in userland panics when the module registers it, on every PHP version:

  • fewer than two members, which the union_type rule in Zend/zend_language_parser.y cannot express
  • a nested union
  • mixed, void or never as a member
  • a duplicate member, or a redundant pair such as bool|false, object|Foo, iterable|array or iterable|Traversable

The last two are the checks zend_compile_typename in Zend/zend_compile.c applies to userland code. PHP does not apply any of them to internal functions.

Default values reach the handler only through named arguments

A default value works with any type hint, or none. It is recorded on PHP 8.0 and later. Older versions ignore it, but the argument is still optional.

In userland, PHP binds every default to its parameter, even when the caller leaves it off:

function my_function(?\MyNamespace\MyInterface $a_class, string $name = 'my_default', bool $optional_bool = false) {
    var_dump(func_get_args(), $name, $optional_bool);
}

my_function(null);
// func_get_args() is [null]
// $name is 'my_default'
// $optional_bool is false

func_get_args() holds only the passed arguments. As the PHP manual puts it, it “does not account for default (non-passed) arguments”.

A phper handler has no parameter variables. Its arguments slice holds what func_get_args() would return, and nothing more:

// All three passed. The handler gets null, 'x', true.
my_function(null, 'x', true);

// $name skipped by name. PHP fills the gap from the declared default, so the
// handler gets null, 'my_default', true.
my_function(null, optional_bool: true);

// Only $a_class passed. The handler gets null, and nothing for $name or
// $optional_bool.
my_function(null);

PHP’s own internal functions work the same way. str_pad declares $pad_string = " ", but the default it uses is a C local variable. The declared default is for reflection and named-argument gaps.

Read optional arguments with arguments.get(n). Indexing past the end of the slice panics, which aborts the PHP process. What to do with a missing argument is up to the handler. This one falls back to the declared defaults, as a userland function would:

use phper::{modules::Module, php_get_module, functions::Argument, echo};
use phper::types::ArgumentTypeHint;

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("my_function", |arguments| -> phper::Result<()> {
        let name = match arguments.get(1) {
            Some(name) => name.expect_z_str()?.to_str()?,
            None => "my_default",
        };
        let optional_bool = match arguments.get(2) {
            Some(optional_bool) => optional_bool.expect_bool()?,
            None => false,
        };
        echo!("{} {}\n", name, optional_bool);
        Ok(())
    })
    .argument(Argument::new("a_class").with_type_hint(ArgumentTypeHint::ClassEntry(String::from(r"\MyNamespace\MyInterface"))).allow_null())
    .argument(Argument::new("name").with_type_hint(ArgumentTypeHint::String).with_default_value("'my_default'"))
    .argument(Argument::new("optional_bool").with_type_hint(ArgumentTypeHint::Bool).optional());

    module
}

Optional arguments must come last

Note the ordering in that example: the two optional arguments come after the required one. That is not a style choice.

PHP derives optionality from position, not from a per-argument flag — it records the index of the last required parameter and treats everything before it as required, however that argument was declared. So an optional argument placed before a required one is promoted back to required, and its default value is never used. This is the same rule the PHP compiler applies to userland functions, where writing it raises a deprecation notice as of PHP 8.0.

use phper::{modules::Module, php_get_module, functions::Argument};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_function("my_function", |_| -> phper::Result<()> {
        Ok(())
    })
    .argument(Argument::new("a"))
    .argument(Argument::new("b").optional())
    .argument(Argument::new("c"));

    module
}

Despite b being declared optional, all three parameters are required, and calling with fewer than three raises ArgumentCountError:

    Function [ <internal:integration> function my_function ] {

      - Parameters [3] {
        Parameter #0 [ <required> $a ]
        Parameter #1 [ <required> $b ]
        Parameter #2 [ <required> $c ]
      }
    }

Declare optional arguments last, so the signature means what it reads as.

Register constants

In PHPER, you can use add_constant to register constants.

use phper::{modules::Module, php_get_module};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_constant("FOO", 100i64);

    module
}

Because in PHP, you can also use copyable values as constants, such as long, double and string, so the value have to implement Scalar.

Register ini settings

In PHPER, you can use add_ini to register ini settings.

use phper::{modules::Module, php_get_module, ini::Policy};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_ini("demo.enable", false, Policy::All);
    module.add_ini("demo.foo", 100, Policy::All);

    module
}

About the policy of setting, you can refer to https://www.php.net/manual/en/configuration.changes.modes.php.

Configure ini settings

The user can configure the ini settings in the php.ini. If not configured, the configuration item will use the default value.

demo.enable = On

You can show the ini settings by php --ri <EXTENSION_NAME>.

demo

version => 0.0.0
authors => PHPER Framework Team:jmjoy <jmjoy@apache.org>

Directive => Local Value => Master Value
demo.enable => 1 => 1
demo.num => 100 => 100

Get ini settings

After the ini settings registered, you can get it by ini_get.

use phper::ini::ini_get;

let _foo = ini_get::<bool>("demo.enable");
let _bar = ini_get::<i64>("demo.foo");

Extension information

By default, PHPER will auto register the MINFO handle, show the info about extension name, version, authors, and display configuration items.

As you execute the command php --ri <EXTENSION_NAME>:

demo

version => 0.0.0
authors => PHPER Framework Team:jmjoy <jmjoy@apache.org>

Directive => Local Value => Master Value
complex.enable => 0 => 0
complex.foo => 100 => 100

If you want to add extra info items, you can use Module::add_info method.

use phper::{modules::Module, php_get_module};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    module.add_info("extra info key", "extra info value");

    module
}

Then build the extension and call php --ri <EXTENSION_NAME>:

demo

version => 0.0.0
authors => PHPER Framework Team:jmjoy <jmjoy@apache.org>
extra info key => extra info value

Directive => Local Value => Master Value
complex.enable => 0 => 0
complex.foo => 100 => 100

The extra info key item is appeared.

Register class

Registering classes is a bit more complicated than others.

First, you have to instantiate the class builder ClassEntity, then register the parent class or implements interfaces, add the properties and methods, finally add it into the Module.

Here is the simplest example:

use phper::{classes::ClassEntity, modules::Module, php_get_module};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    let foo = ClassEntity::new("Foo");

    module.add_class(foo);

    module
}

Similarly in PHP:

<?php

class Foo {}

Extends & implements

To allow a class to extend another, you can use ClassEntity.extends(StateClass<T>). A StateClass can either be obtained by registering your own class against the module, or by looking up the class by name (for example, for PHP built-in classes like Exception).

If you want class Foo extends Bar, and implements interface Stringable:

use phper::classes::{ClassEntity, ClassEntry, Interface};
use phper::{modules::Module, php_get_module};

let mut module = Module::new("test", "0.1", "");

let bar = module.add_class(ClassEntity::new("Bar"));
let mut foo = ClassEntity::new("Foo");
foo.extends(bar);
foo.implements(Interface::from_name("Stringable"));

You should implement the method Stringable::__toString after implementing Stringable, otherwise the class Foo will become abstract class.

Final classes

To forbid extending a class, use ClassEntity::set_final:

use phper::classes::ClassEntity;

let mut foo = ClassEntity::new("Foo");
foo.set_final();

Userland code extending Foo then fails to compile with a fatal error, exactly as for a final class declared in PHP. final classes are available in every PHP version PHPER supports, so this needs no minimum version.

Note that this applies to classes registered by your extension too: if another ClassEntity extends Foo, the error is raised while the module starts up rather than when userland calls into it.

Readonly classes

To make every property of a class readonly, use ClassEntity::set_readonly:

use phper::classes::{ClassEntity, Visibility};
use phper::types::PropertyTypeHint;

let mut foo = ClassEntity::new("Foo");
foo.set_readonly();
foo.add_typed_property("bar", Visibility::Public, PropertyTypeHint::Int, None);

Similarly in PHP:

<?php

readonly class Foo {
    public int $bar;
}

As in PHP, every property of a readonly class must be typed, non-static and have no default, or the module panics at startup. Dynamic properties are refused.

Readonly classes need PHP 8.2. On PHP 8.0 and 8.1 only dynamic properties are refused, and on PHP 7 the class is unchanged.

Add properties

Due to the limitation of PHP, you can only use copyable values as class properties.

use phper::classes::{ClassEntity, ClassEntry, Visibility};

let mut foo = ClassEntity::new("Foo");
foo.add_property("prop", Visibility::Public, "the prop value");

Typed properties

add_typed_property declares a property with a type. Its default is Option<Scalar>, and None leaves the property uninitialized, so reading it before a write throws Error. Call allow_null to make the type nullable.

use phper::classes::{ClassEntity, Visibility};
use phper::types::PropertyTypeHint;

let mut foo = ClassEntity::new("Foo");
foo.add_typed_property("count", Visibility::Public, PropertyTypeHint::Int, Some(0.into()));
foo.add_typed_property("name", Visibility::Public, PropertyTypeHint::String, None);
foo.add_typed_property(
    "parent",
    Visibility::Private,
    PropertyTypeHint::ClassEntry(String::from(r"\MyNamespace\Node")),
    Some(().into()),
)
.allow_null();

Similarly in PHP:

<?php

class Foo {
    public int $count = 0;
    public string $name;
    private ?\MyNamespace\Node $parent = null;
}

The default is checked against the type as PHP checks a userland one, and the module panics at startup if it does not match. A Mixed property takes any default. A null default needs allow_null. An int default on a Float property is converted to float. Array, Object, Iterable and class-typed properties can only default to null, since Scalar holds neither arrays nor objects. The check runs on every PHP version, including PHP 7.

Typed properties need PHP 8.0. On PHP 7 the property is declared untyped, with its default, or null if it has none.

Readonly properties

add_readonly_property declares a typed, uninitialized property that can be written once.

use phper::classes::{ClassEntity, Visibility};
use phper::functions::Argument;
use phper::types::PropertyTypeHint;

let mut foo = ClassEntity::new("Foo");
foo.add_readonly_property("id", Visibility::Public, PropertyTypeHint::Int);
foo.add_method("__construct", Visibility::Public, |this, arguments| {
    this.set_property("id", arguments[0].clone());
    Ok::<_, phper::Error>(())
})
.argument(Argument::new("id"));

Similarly in PHP:

<?php

class Foo {
    public readonly int $id;

    public function __construct($id) {
        $this->id = $id;
    }
}

Readonly properties need PHP 8.1. On PHP 8.0 the property is a plain typed property, and on PHP 7 an untyped one.

PHP does not allow a default on a readonly property, nor a static one, so there is no way to declare either.

Before PHP 8.4, a method of Foo cannot initialize the property on an instance of a userland subclass of Foo. set_property uses the object’s class as the scope, and PHP 8.1 to 8.3 allow initialization only from the declaring class.

Promoted constructor properties are a compile-time feature of PHP and have no equivalent here. Declare the property and write it from the constructor.

Typed static properties

add_static_typed_property declares a static property with a type. It takes the same arguments as add_typed_property, and its default is checked the same way.

use phper::classes::{ClassEntity, Visibility};
use phper::types::PropertyTypeHint;

let mut foo = ClassEntity::new("Foo");
foo.add_static_typed_property("count", Visibility::Public, PropertyTypeHint::Int, Some(0.into()));
foo.add_static_typed_property("name", Visibility::Private, PropertyTypeHint::String, None);

Similarly in PHP:

<?php

class Foo {
    public static int $count = 0;
    private static string $name;
}

Typed static properties need PHP 8.0. On PHP 7 the property is declared untyped, with its default, or null if it has none.

PHP checks the type when userland assigns the property. ClassEntry::set_static_property does not, so a value of the wrong type is stored as given.

Add methods

Adding class methods is similar with adding module functions, the difference is that adding class methods increases Visibility and $this object.

use phper::classes::{ClassEntity, ClassEntry, Visibility};
use phper::objects::StateObj;
use phper::values::ZVal;

let mut foo = ClassEntity::new("Foo");
foo.add_method(
    "getProp",
    Visibility::Public,
    |this: &mut StateObj<()>, _: &mut [ZVal]| {
        let prop = this.get_property("foo");
        Ok::<_, phper::Error>(prop.clone())
    },
);

Adding static class methods is more like adding module functions, because there is no $this variable.

use phper::classes::{ClassEntity, ClassEntry, Visibility};
use phper::functions::Argument;
use phper::values::ZVal;

let mut foo = ClassEntity::new("Foo");
foo.add_static_method(
    "staticSayHello",
    Visibility::Public,
    |arguments: &mut [ZVal]| {
        let name = arguments[0].expect_z_str()?.to_str()?;
        Ok::<_, phper::Error>(format!("Hello, {}!\n", name))
    },
).argument(Argument::new("name"));

Argument and return type modifiers

Methods may add argument and return typehints as per functions. For example:

use phper::classes::{ClassEntity, ClassEntry, Visibility};
use phper::functions::{Argument, ReturnType};
use phper::types::{ArgumentTypeHint, ReturnTypeHint};

let mut foo = ClassEntity::new("Foo");
foo.add_method(
    "test",
    Visibility::Public,
    |_this, _arguments| -> phper::Result<()> {
        Ok(())
    },
)
.argument(Argument::new("a_string").with_type_hint(ArgumentTypeHint::String))
.argument(Argument::new("an_interface").with_type_hint(ArgumentTypeHint::ClassEntry(String::from(r"\MyNamespace\MyInterface"))))
.return_type(ReturnType::new(ReturnTypeHint::Bool).allow_null());

Add constants

Interfaces can have public constants. Value can be string|int|bool|float|null.

use phper::classes::ClassEntity;

let mut foo = ClassEntity::new("Foo");
foo.add_constant("ONE", "one");
foo.add_constant("TWO", 2);
foo.add_constant("THREE", 3.0);

Handle state

The ClassEntity represents the class entry hold the state as generic type, so you can wrap the Rust struct as state in PHP class, which is the common usage of class in php extensions (if using C/C++ to develop PHP extension, the PHP class commonly wrap the C/C++ pointer).

Imagine that we encapsulate Rust’s HashMap for PHP.

First, we register the class hold the state with type HashMap, then add the method to insert key value pair.

use std::collections::HashMap;
use phper::classes::{ClassEntity, ClassEntry, Visibility};
use phper::functions::Argument;

let mut class =
ClassEntity::<HashMap<String, String>>::new_with_state_constructor(
    "MyHashMap", HashMap::new);

class.add_method(
    "insert",
    Visibility::Public,
    |this, arguments| {
        let key = arguments[0].expect_z_str()?.to_str()?.to_string();
        let value = arguments[1].expect_z_str()?.to_str()?.to_string();

        let state = this.as_mut_state();
        state.insert(key, value);

        Ok::<_, phper::Error>(())
    },
)
.argument(Argument::new("key"))
.argument(Argument::new("value"));

Equivalent to the following PHP code (hides the implementation details):

<?php

class MyHashMap {

    public void insert() {
        // ...
    }

}

Circular class dependencies

If you wish to register classes which depend on each other, you can retrieve the bound class (StateClass<T>) from a ClassEntity, and use it in functions and methods:

use phper::{
    classes::{ClassEntity, StateClass, Visibility},
    modules::Module,
};

let mut module = Module::new(
    env!("CARGO_CRATE_NAME"),
    env!("CARGO_PKG_VERSION"),
    env!("CARGO_PKG_AUTHORS"),
);

let mut a_cls = ClassEntity::new("A");
let mut b_cls = ClassEntity::new("B");
let a_bound_class = a_cls.bound_class();
let b_bound_class = b_cls.bound_class();

a_cls.add_static_method("createB", Visibility::Public, move |_| {
    let object = b_bound_class.init_object()?;
    Ok::<_, phper::Error>(object)
});
b_cls.add_static_method("createA", Visibility::Public, move |_| {
    let object = a_bound_class.init_object()?;
    Ok::<_, phper::Error>(object)
});

module.add_class(a_cls);
module.add_class(b_cls);

This is equivalent to the following PHP code:

class A {
  public static function createB(): B {
    return new B();
  }
}
class B {
  public static function createA(): A {
    return new A();
  }
}

Register interface

Registering interfaces is similar to registering classes.

First, you have to instantiate the class builder. InterfaceEntity, then extends interfaces (if there are), add public abstract methods, finally add it into the Module.

Here is the simplest example:

use phper::{classes::InterfaceEntity, modules::Module, php_get_module};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    let foo = InterfaceEntity::new("Foo");

    module.add_interface(foo);

    module
}

Similarly in PHP:

<?php

interface Foo {}

Extends interfaces

If you want the interface Foo extends ArrayAccess and Iterator interfaces.

use phper::classes::{Interface, InterfaceEntity, ClassEntry};

let mut foo = InterfaceEntity::new("Foo");
foo.extends(Interface::from_name("ArrayAccess"));
foo.extends(Interface::from_name("Iterator"));

Same as:

<?php

interface Foo extends ArrayAccess, Iterator {}

Add methods

Interface can add public abstract methods, and public static abstract methods.

use phper::classes::{InterfaceEntity, ClassEntry, Visibility};
use phper::functions::Argument;
use phper::objects::StateObj;
use phper::values::ZVal;

let mut foo = InterfaceEntity::new("Foo");
foo.add_method("doSomethings").argument(Argument::new("name"));
foo.add_static_method("test");

Note that abstract has no method body, so you don’t need to add the handler to the method.

Add constants

Interfaces can have public constants. Value can be string|int|bool|float|null.

use phper::classes::InterfaceEntity;

let mut foo = InterfaceEntity::new("Foo");
foo.add_constant("ONE", "one");
foo.add_constant("TWO", 2);
foo.add_constant("THREE", 3.0);

Register Enums

PHP 8.1 and above introduced the Enum functionality. PHPER allowing you to create PHP enums using Rust code.

In PHPER, you can use the add_enum method to register enums. According to PHP’s enum specification, PHPER supports three types of enums:

  1. Pure enums (without values)
  2. Integer-backed enums
  3. String-backed enums

Creating Pure Enums

Pure enums are the simplest type of enum, having only member names without associated values. Use EnumEntity<()> to create a pure enum (or simply use EnumEntity::new() since () is the default type parameter).

use phper::{modules::Module, php_get_module, enums::EnumEntity, classes::Visibility};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    // Create a pure enum
    let mut status = EnumEntity::new("Status");
    
    // Add enum cases (without values)
    status.add_case("PENDING", ());
    status.add_case("ACTIVE", ());
    status.add_case("INACTIVE", ());
    
    // Register the enum to the module
    module.add_enum(status);

    module
}

This is equivalent to the following PHP code:

enum Status {
    case PENDING;
    case ACTIVE;
    case INACTIVE;
}

Creating Integer-Backed Enums

Integer-backed enums associate each enum member with an integer value. Use EnumEntity<i64> to create an integer-backed enum.

use phper::{modules::Module, php_get_module, enums::EnumEntity};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    // Create an integer-backed enum
    let mut level = EnumEntity::<i64>::new("Level");
    
    // Add enum cases with their associated integer values
    level.add_case("LOW", 1);
    level.add_case("MEDIUM", 5);
    level.add_case("HIGH", 10);
    
    // Register the enum to the module
    module.add_enum(level);

    module
}

This is equivalent to the following PHP code:

enum Level: int {
    case LOW = 1;
    case MEDIUM = 5;
    case HIGH = 10;
}

Creating String-Backed Enums

String-backed enums associate each enum member with a string value. Use EnumEntity<String> to create a string-backed enum.

use phper::{modules::Module, php_get_module, enums::EnumEntity};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    // Create a string-backed enum
    let mut color = EnumEntity::<String>::new("Color");
    
    // Add enum cases with their associated string values
    color.add_case("RED", "FF0000".to_string());
    color.add_case("GREEN", "00FF00".to_string());
    color.add_case("BLUE", "0000FF".to_string());
    
    // Register the enum to the module
    module.add_enum(color);

    module
}

This is equivalent to the following PHP code:

enum Color: string {
    case RED = "FF0000";
    case GREEN = "00FF00";
    case BLUE = "0000FF";
}

Adding Constants

Enums can contain constants. Use the add_constant method to add constants to an enum.

use phper::{modules::Module, php_get_module, enums::EnumEntity};

let mut status = EnumEntity::new("Status");

// Add enum cases
status.add_case("PENDING", ());
status.add_case("ACTIVE", ());

// Add constants
status.add_constant("VERSION", "1.0.0");
status.add_constant("MAX_ATTEMPTS", 3);

This is equivalent to the following PHP code:

enum Status {
    case PENDING;
    case ACTIVE;
    
    public const VERSION = "1.0.0";
    public const MAX_ATTEMPTS = 3;
}

Adding Static Methods

You can add static methods to enums. Use the add_static_method method to add a static method to an enum.

use phper::{modules::Module, php_get_module, enums::EnumEntity, classes::Visibility};
use std::convert::Infallible;

let mut status = EnumEntity::new("Status");

// Add enum cases
status.add_case("PENDING", ());
status.add_case("ACTIVE", ());

// Add static method
status.add_static_method("getDescription", Visibility::Public, |_| {
    Ok::<_, Infallible>("Status enumeration for tracking item states")
});

This is equivalent to the following PHP code:

enum Status {
    case PENDING;
    case ACTIVE;
    
    public static function getDescription(): string {
        return "Status enumeration for tracking item states";
    }
}

Implementing Interfaces

You can make enums implement interfaces. Use the implements method to make an enum implement a specific interface.

use phper::{modules::Module, php_get_module, enums::EnumEntity, classes::Interface};

let mut color = EnumEntity::<String>::new("Color");

// Add enum cases
color.add_case("RED", "FF0000".to_string());
color.add_case("GREEN", "00FF00".to_string());

// Implement interface
color.implements(Interface::from_name("JsonSerializable"));

// Note: You need to add necessary methods to satisfy interface requirements
// For example, JsonSerializable interface requires the implementation of jsonSerialize method

Using Built-in Enum Methods

PHP enums come with some built-in methods. Pure enums (UnitEnum) have the cases() method, while backed enums (BackedEnum) additionally have the from() and tryFrom() methods.

// Examples of using built-in methods in PHP
$allCases = Color::cases(); // Returns an array of all enum cases

// Only available for backed enums
$colorFromValue = Color::from("FF0000"); // Returns RED
$colorOrNull = Color::tryFrom("INVALID"); // Returns null (when the value doesn't exist)

Using EnumCase for Direct Access

When you call add_case() on an enum entity, it returns an EnumCase instance that you can use for direct access to that case later. This is more efficient than looking up the enum case by name each time you need it.

Here’s an example showing how to use EnumCase within static methods of the enum:

use phper::{
    modules::Module, 
    php_get_module, 
    enums::EnumEntity, 
    classes::Visibility,
    alloc::ToRefOwned,
};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    // Create a pure enum
    let mut pure_enum_entity = EnumEntity::new("PureEnum");
    
    // Store references to enum cases when adding them
    let one_case = pure_enum_entity.add_case("ONE", ());
    let _two_case = pure_enum_entity.add_case("TWO", ());
    
    // Add static method that returns the ONE case
    pure_enum_entity.add_static_method("getOneCase", Visibility::Public, {
        // Clone the EnumCase because it will be moved into the closure
        move |_| {
            // Get the case object directly from EnumCase
            let one_obj = one_case.clone().get_mut_case();
            let result = one_obj.to_ref_owned();
            phper::ok(result)
        }
    });
    
    // Register the enum to the module
    module.add_enum(pure_enum_entity);

    // Create an int-backed enum
    let mut int_enum_entity = EnumEntity::<i64>::new("IntEnum");
    
    // Store reference to LOW case
    let low_case = int_enum_entity.add_case("LOW", 10);
    let _high_case = int_enum_entity.add_case("HIGH", 100);
    
    // Add static method that returns the LOW case
    int_enum_entity.add_static_method("getLowCase", Visibility::Public, {
        move |_| {
            let low_obj = low_case.clone().get_mut_case();
            let result = low_obj.to_ref_owned();
            phper::ok(result)
        }
    });
    
    // Register the enum to the module
    module.add_enum(int_enum_entity);

    module
}

This creates PHP enums with static methods that can access specific cases:

enum PureEnum {
    case ONE;
    case TWO;
    
    public static function getOneCase(): self {
        return self::ONE;
    }
}

enum IntEnum: int {
    case LOW = 10;
    case HIGH = 100;
    
    public static function getLowCase(): self {
        return self::LOW;
    }
}

Using Enum::from_name

If you don’t have direct access to the EnumCase, you can use Enum::from_name() to get an enum by its name, and then use get_case() or get_mut_case() to access specific cases:

use phper::{
    enums::Enum,
    enums::EnumEntity,
    classes::Visibility,
    alloc::ToRefOwned,
};

fn create_enum_with_dynamic_lookup() -> EnumEntity {
    let mut enum_entity = EnumEntity::new("DynamicEnum");
    enum_entity.add_case("ONE", ());
    enum_entity.add_case("TWO", ());
    
    // Add a static method that looks up cases dynamically
    enum_entity.add_static_method("getCaseByName", Visibility::Public, |args| {
        // Get case name from parameters
        let case_name = args[0].expect_z_str()?.to_string_lossy();
        
        // Use Enum::from_name to get the enum
        let mut enum_obj = Enum::from_name("DynamicEnum");
        
        // Try to get the requested case
        let case = unsafe { enum_obj.get_mut_case(&case_name)? };
        let result = case.to_ref_owned();
        
        phper::ok(result)
    });
    
    enum_entity
}

Important: The get_case() and get_mut_case() methods on Enum are marked as unsafe because they can cause segmentation faults if the case doesn’t exist.

Bound Enum

You can use the bound_enum() method to get a reference to the enum that can be used in methods or functions:

use phper::{enums::EnumEntity, classes::Visibility, alloc::ToRefOwned};

pub fn make_status_enum() -> EnumEntity {
    let mut enum_entity = EnumEntity::new("Status");
    enum_entity.add_case("Active", ());
    enum_entity.add_case("Inactive", ());
    
    // Get a reference to the enum that will be created
    let status_enum = enum_entity.bound_enum();
    
    // Add a static method that uses the bound enum
    enum_entity.add_static_method("getActiveCase", Visibility::Public, move |_| {
        // Use the bound enum to get the Active case
        let active_case = unsafe { status_enum.clone().get_mut_case("Active")? };
        phper::ok(active_case.to_ref_owned())
    });
    
    enum_entity
}

Complete Example

Here’s a comprehensive example using both pure and backed enums with static methods:

use phper::{
    modules::Module, 
    php_get_module, 
    enums::EnumEntity, 
    classes::Visibility,
    alloc::ToRefOwned,
};

#[php_get_module]
pub fn get_module() -> Module {
    let mut module = Module::new(
        env!("CARGO_CRATE_NAME"),
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_AUTHORS"),
    );

    // Pure enum
    let mut status = EnumEntity::new("Status");
    let pending_case = status.add_case("PENDING", ());
    let active_case = status.add_case("ACTIVE", ());
    let inactive_case = status.add_case("INACTIVE", ());
    
    // Add constants
    status.add_constant("VERSION", "1.0.0");
    
    // Add static method that returns the active state
    status.add_static_method("getActiveStatus", Visibility::Public, {
        move |_| {
            let obj = active_case.clone().get_mut_case();
            phper::ok(obj.to_ref_owned())
        }
    });
    
    // Add static method that returns status description
    status.add_static_method("getDescription", Visibility::Public, |_| {
        phper::ok("Status enumeration")
    });
    
    // Integer-backed enum
    let mut level = EnumEntity::<i64>::new("Level");
    let low_case = level.add_case("LOW", 1);
    let medium_case = level.add_case("MEDIUM", 5);
    let high_case = level.add_case("HIGH", 10);
    
    // Add static method that returns level by value
    level.add_static_method("getLevelByValue", Visibility::Public, {
        move |args| {
            let value: i64 = args[0].expect_long()?;
            let case_obj = match value {
                v if v < 3 => low_case.clone().get_mut_case(),
                v if v < 8 => medium_case.clone().get_mut_case(),
                _ => high_case.clone().get_mut_case(),
            };
            phper::ok(case_obj.to_ref_owned())
        }
    });
    
    // Register enums to the module
    module.add_enum(status);
    module.add_enum(level);

    module
}

Note: PHP enums require PHP 8.1 or higher. Make sure your extension sets the correct PHP version requirements.