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

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!