ext-php-rs 0.17.0

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# `#[php_interface]` Attribute

You can export a `Trait` block to PHP. This exports all methods as well as
constants to PHP on the interface. Trait method SHOULD NOT contain default
implementations, as these are not supported in PHP interfaces.

## Options

By default all constants are renamed to `UPPER_CASE` and all methods are renamed to
`camelCase`. This can be changed by passing the `change_method_case` and
`change_constant_case` as `#[php]` attributes on the `impl` block. The options are:

- `#[php(change_method_case = "snake_case")]` - Renames the method to snake case.
- `#[php(change_constant_case = "snake_case")]` - Renames the constant to snake case.

See the [`name` and `change_case`](./php.md#name-and-change_case) section for a list of all
available cases.

The macro itself takes no arguments: `#[php_interface(name = "Foo")]` is a
compile error. Put the options in `#[php(...)]` on the trait.

## Methods

A trait method accepts the `name`, `change_case`, `defaults`, `optional`,
`sensitive` and `vis` options. Interfaces cannot declare property accessors or constructors, so
`getter`, `setter` and `constructor` are compile errors here. See
[`php_impl`](./impl.md#) for how each accepted option behaves.

## Constants

A trait constant accepts the `name` and `change_case` options. Interface
constants are always public, so `vis` is a compile error here. See
[`php_impl`](./impl.md#constants) for the value types.

## Example

Define an example trait with methods and constant:

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{prelude::*, types::ZendClassObject};


#[php_interface]
#[php(name = "Rust\\TestInterface")]
trait Test {
    const TEST: &'static str = "TEST";

    fn co();

    #[php(defaults(value = 0))]
    fn set_value(&mut self, value: i32);
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .interface::<PhpInterfaceTest>()
}

# fn main() {}
```

Using our newly created interface in PHP:

```php
<?php

assert(interface_exists("Rust\TestInterface"));

class B implements Rust\TestInterface {

    public static function co() {}

    public function setValue(?int $value = 0) {

    }
}

```

## Interface Inheritance

PHP interfaces can extend other interfaces. You can achieve this in two ways:

### Using `#[php(extends(...))]`

Use the `extends` attribute to extend a built-in PHP interface or another Rust-defined interface.
Generated stubs write each parent interface name as a fully qualified name, with a leading `\`.
A leading `\` in `stub = "..."` is optional.

For built-in PHP interfaces, use the explicit form:

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;
use ext_php_rs::zend::ce;

#[php_interface]
#[php(extends(ce = ce::throwable, stub = "\\Throwable"))]
#[php(name = "MyException")]
trait MyExceptionInterface {
    fn get_error_code(&self) -> i32;
}

# fn main() {}
```

For Rust-defined interfaces, you can use the simpler type syntax:

```rust,ignore
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

#[php_interface]
trait BaseInterface {
    fn base_method(&self) -> i32;
}

#[php_interface]
#[php(extends(BaseInterface))]
trait ExtendedInterface {
    fn extended_method(&self) -> String;
}

# fn main() {}
```

### Using Rust Trait Bounds

You can also use Rust's trait bound syntax. When a trait marked with `#[php_interface]`
has supertraits, the PHP interface will automatically extend those parent interfaces:

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

#[php_interface]
#[php(name = "Rust\\ParentInterface")]
trait ParentInterface {
    fn parent_method(&self) -> String;
}

// ChildInterface extends ParentInterface in PHP
#[php_interface]
#[php(name = "Rust\\ChildInterface")]
trait ChildInterface: ParentInterface {
    fn child_method(&self) -> String;
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .interface::<PhpInterfaceParentInterface>()
        .interface::<PhpInterfaceChildInterface>()
}

# fn main() {}
```

In PHP:

```php
<?php

// ChildInterface extends ParentInterface
assert(is_a('Rust\ChildInterface', 'Rust\ParentInterface', true));
```

# `#[php_impl_interface]` Attribute

The `#[php_impl_interface]` attribute allows a Rust class to implement a custom PHP
interface defined with `#[php_interface]`. This creates a relationship where PHP's
`instanceof` and `is_a()` recognize the implementation.

**Key feature**: The macro automatically registers the trait methods as PHP methods
on the class. You don't need to duplicate them in a separate `#[php_impl]` block.

## Example

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

// Define a custom interface
#[php_interface]
#[php(name = "Rust\\Greetable")]
trait Greetable {
    fn greet(&self) -> String;
}

// Define a class
#[php_class]
#[php(name = "Rust\\Greeter")]
pub struct Greeter {
    name: String,
}

#[php_impl]
impl Greeter {
    pub fn __construct(name: String) -> Self {
        Self { name }
    }

    // Note: No need to add greet() here - it's automatically
    // registered by #[php_impl_interface] below
}

// Implement the interface for the class
// This automatically registers greet() as a PHP method
#[php_impl_interface]
impl Greetable for Greeter {
    fn greet(&self) -> String {
        format!("Hello, {}!", self.name)
    }
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .interface::<PhpInterfaceGreetable>()
        .class::<Greeter>()
}

# fn main() {}
```

Using in PHP:

```php
<?php

$greeter = new Rust\Greeter("World");

// instanceof works
assert($greeter instanceof Rust\Greetable);

// is_a() works
assert(is_a($greeter, 'Rust\Greetable'));

// The greet() method is available (registered by #[php_impl_interface])
echo $greeter->greet(); // Output: Hello, World!

// Can be used as type hint
function greet(Rust\Greetable $obj): void {
    echo $obj->greet();
}

greet($greeter);
```

## When to Use

- Use `#[php_impl_interface]` for custom interfaces you define with `#[php_interface]`
- Use `#[php(implements(ce = ...))]` on `#[php_class]` for built-in PHP interfaces
  like `Iterator`, `ArrayAccess`, `Countable`, etc.

See the [Classes documentation](./classes.md#implementing-an-interface) for examples
of implementing built-in interfaces.

## Cross-Crate Support

The `#[php_impl_interface]` macro supports cross-crate interface discovery via the
[`inventory`](https://crates.io/crates/inventory) crate. This means you can define
an interface in one crate and implement it in another crate, and the implementation
will be automatically discovered at link time.

### Example: Defining an Interface in a Library Crate

First, create a library crate that defines the interface:

```toml
# my-interfaces/Cargo.toml
[package]
name = "my-interfaces"
version = "0.1.0"

[dependencies]
ext-php-rs = "0.15"
```

```rust,no_run,ignore
// my-interfaces/src/lib.rs
use ext_php_rs::prelude::*;

/// A serializable interface that can convert objects to JSON.
#[php_interface]
#[php(name = "MyInterfaces\\Serializable")]
pub trait Serializable {
    fn to_json(&self) -> String;
}

// Re-export the generated PHP interface struct for consumers
pub use PhpInterfaceSerializable;
```

### Example: Implementing the Interface in Another Crate

Now create your extension crate that implements the interface:

```toml
# my-extension/Cargo.toml
[package]
name = "my-extension"
version = "0.1.0"

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

[dependencies]
ext-php-rs = "0.15"
my-interfaces = { path = "../my-interfaces" }
```

```rust,no_run,ignore
// my-extension/src/lib.rs
use ext_php_rs::prelude::*;
use my_interfaces::Serializable;

#[php_class]
#[php(name = "MyExtension\\User")]
pub struct User {
    name: String,
    email: String,
}

#[php_impl]
impl User {
    pub fn __construct(name: String, email: String) -> Self {
        Self { name, email }
    }

    // Note: No need to add to_json() here - it's automatically
    // registered by #[php_impl_interface] below
}

// Register the interface implementation
// This automatically registers to_json() as a PHP method
#[php_impl_interface]
impl Serializable for User {
    fn to_json(&self) -> String {
        format!(r#"{{"name":"{}","email":"{}"}}"#, self.name, self.email)
    }
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
        // Register the interface from the library crate
        .interface::<my_interfaces::PhpInterfaceSerializable>()
        .class::<User>()
}
```

### Using in PHP

```php
<?php

use MyExtension\User;
use MyInterfaces\Serializable;

$user = new User("John", "john@example.com");

// instanceof works across crates
assert($user instanceof Serializable);

// Type hints work
function serialize_object(Serializable $obj): string {
    return $obj->toJson();
}

echo serialize_object($user);
// Output: {"name":"John","email":"john@example.com"}
```

### Important Notes

1. **Automatic method registration**: The `#[php_impl_interface]` macro automatically
   registers all trait methods as PHP methods on the class. You don't need to duplicate
   them in a `#[php_impl]` block.

2. **Interface registration**: The interface must be registered in the `#[php_module]`
   function using `.interface::<PhpInterfaceName>()`.

3. **Link-time discovery**: The `inventory` crate uses link-time registration for
   interface discovery, so all implementations are automatically discovered when the
   final binary is linked.

4. **Method names**: Each method gets the PHP name that `#[php_interface]` declared
   for it. The trait's `change_method_case` and the `name` or `change_case` of a
   trait method apply to the class too. `#[php_impl_interface]` takes no arguments.

5. **Sensitive parameters**: `#[php(sensitive(...))]` on a trait method also
   applies to the class method, so exception traces from the class hide the
   same arguments. The macro marks the argument at the same position, thus the
   parameter names in the `impl` can be different. A PHP class that implements
   the interface does not get the attribute, because PHP does not copy parameter
   attributes from an interface. Declare `#[\SensitiveParameter]` on its method.