ext-php-rs 0.15.11

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
405
406
407
408
409
# Observer API

The Observer API allows you to build profilers, tracers, and instrumentation tools
that observe PHP function calls and errors. This is useful for:

- Performance profiling
- Request tracing (APM)
- Error monitoring
- Code coverage tools
- Debugging tools

## Enabling the Feature

The Observer API is behind a feature flag. Add it to your `Cargo.toml`:

```toml
[dependencies]
ext-php-rs = { version = "0.15", features = ["observer"] }
```

## Function Call Observer

Implement the `FcallObserver` trait to observe function calls:

```rust,ignore
use ext_php_rs::prelude::*;
use ext_php_rs::types::Zval;
use ext_php_rs::zend::ExecuteData;
use std::sync::atomic::{AtomicU64, Ordering};

struct CallCounter {
    count: AtomicU64,
}

impl CallCounter {
    fn new() -> Self {
        Self {
            count: AtomicU64::new(0),
        }
    }
}

impl FcallObserver for CallCounter {
    fn should_observe(&self, info: &FcallInfo) -> bool {
        !info.is_internal
    }

    fn begin(&self, _execute_data: &ExecuteData) {
        self.count.fetch_add(1, Ordering::Relaxed);
    }

    fn end(&self, _execute_data: &ExecuteData, _retval: Option<&Zval>) {}
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.fcall_observer(CallCounter::new)
}
```

### The `FcallObserver` Trait

| Method | Description |
|--------|-------------|
| `should_observe(&self, info: &FcallInfo) -> bool` | Called once per function definition. Result is cached by PHP. |
| `begin(&self, execute_data: &ExecuteData)` | Called when function begins execution. |
| `end(&self, execute_data: &ExecuteData, retval: Option<&Zval>)` | Called when function ends (even on exceptions). |

### `FcallInfo` - Function Metadata

| Field | Type | Description |
|-------|------|-------------|
| `function_name` | `Option<&str>` | Function name (None for anonymous/main) |
| `class_name` | `Option<&str>` | Class name for methods |
| `filename` | `Option<&str>` | Source file (None for internal functions) |
| `lineno` | `u32` | Line number (0 for internal functions) |
| `is_internal` | `bool` | True for built-in PHP functions |

## Error Observer

Implement the `ErrorObserver` trait to observe PHP errors:

```rust,ignore
use ext_php_rs::prelude::*;
use std::sync::atomic::{AtomicU64, Ordering};

struct ErrorTracker {
    fatal_count: AtomicU64,
    warning_count: AtomicU64,
}

impl ErrorTracker {
    fn new() -> Self {
        Self {
            fatal_count: AtomicU64::new(0),
            warning_count: AtomicU64::new(0),
        }
    }
}

impl ErrorObserver for ErrorTracker {
    fn should_observe(&self, error_type: ErrorType) -> bool {
        (ErrorType::FATAL | ErrorType::WARNING).contains(error_type)
    }

    fn on_error(&self, error: &ErrorInfo) {
        if ErrorType::FATAL.contains(error.error_type) {
            self.fatal_count.fetch_add(1, Ordering::Relaxed);

            if let Some(trace) = error.backtrace() {
                for frame in trace {
                    eprintln!("  at {}:{}",
                        frame.file.as_deref().unwrap_or("<internal>"),
                        frame.line
                    );
                }
            }
        } else {
            self.warning_count.fetch_add(1, Ordering::Relaxed);
        }
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.error_observer(ErrorTracker::new)
}
```

### The `ErrorObserver` Trait

| Method | Description |
|--------|-------------|
| `should_observe(&self, error_type: ErrorType) -> bool` | Filter which error types to observe. |
| `on_error(&self, error: &ErrorInfo)` | Called when an observed error occurs. |

### `ErrorType` - Error Level Bitflags

```rust,ignore
ErrorType::ERROR           // E_ERROR
ErrorType::WARNING         // E_WARNING
ErrorType::PARSE           // E_PARSE
ErrorType::NOTICE          // E_NOTICE
ErrorType::CORE_ERROR      // E_CORE_ERROR
ErrorType::CORE_WARNING    // E_CORE_WARNING
ErrorType::COMPILE_ERROR   // E_COMPILE_ERROR
ErrorType::COMPILE_WARNING // E_COMPILE_WARNING
ErrorType::USER_ERROR      // E_USER_ERROR
ErrorType::USER_WARNING    // E_USER_WARNING
ErrorType::USER_NOTICE     // E_USER_NOTICE
ErrorType::RECOVERABLE_ERROR // E_RECOVERABLE_ERROR
ErrorType::DEPRECATED      // E_DEPRECATED
ErrorType::USER_DEPRECATED // E_USER_DEPRECATED

// Convenience groups
ErrorType::ALL   // All error types
ErrorType::FATAL // ERROR | CORE_ERROR | COMPILE_ERROR | USER_ERROR | RECOVERABLE_ERROR | PARSE
ErrorType::CORE  // CORE_ERROR | CORE_WARNING
```

### `ErrorInfo` - Error Metadata

| Field | Type | Description |
|-------|------|-------------|
| `error_type` | `ErrorType` | The error level/severity |
| `filename` | `Option<&str>` | Source file where error occurred |
| `lineno` | `u32` | Line number |
| `message` | `&str` | The error message |

### Lazy Backtrace

The `backtrace()` method captures the PHP call stack on demand:

```rust,ignore
fn on_error(&self, error: &ErrorInfo) {
    if let Some(trace) = error.backtrace() {
        for frame in trace {
            println!("{}::{}() at {}:{}",
                frame.class.as_deref().unwrap_or(""),
                frame.function.as_deref().unwrap_or("<main>"),
                frame.file.as_deref().unwrap_or("<internal>"),
                frame.line
            );
        }
    }
}
```

The backtrace is only captured when called, so there's zero cost if unused.

## Exception Observer

Implement the `ExceptionObserver` trait to observe thrown PHP exceptions:

```rust,ignore
use ext_php_rs::prelude::*;
use std::sync::atomic::{AtomicU64, Ordering};

struct ExceptionTracker {
    exception_count: AtomicU64,
}

impl ExceptionTracker {
    fn new() -> Self {
        Self {
            exception_count: AtomicU64::new(0),
        }
    }
}

impl ExceptionObserver for ExceptionTracker {
    fn on_exception(&self, exception: &ExceptionInfo) {
        self.exception_count.fetch_add(1, Ordering::Relaxed);
        eprintln!("[EXCEPTION] {}: {} at {}:{}",
            exception.class_name,
            exception.message.as_deref().unwrap_or("<no message>"),
            exception.file.as_deref().unwrap_or("<unknown>"),
            exception.line
        );
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.exception_observer(ExceptionTracker::new)
}
```

### The `ExceptionObserver` Trait

| Method | Description |
|--------|-------------|
| `on_exception(&self, exception: &ExceptionInfo)` | Called when an exception is thrown, before any catch blocks. |

### `ExceptionInfo` - Exception Metadata

| Field | Type | Description |
|-------|------|-------------|
| `class_name` | `String` | Exception class name (e.g., "RuntimeException") |
| `message` | `Option<String>` | The exception message |
| `code` | `i64` | The exception code |
| `file` | `Option<String>` | Source file where thrown |
| `line` | `u32` | Line number where thrown |

### Exception Backtrace

The `backtrace()` method captures the PHP call stack at exception throw time:

```rust,ignore
impl ExceptionObserver for MyObserver {
    fn on_exception(&self, exception: &ExceptionInfo) {
        eprintln!("[EXCEPTION] {}: {}",
            exception.class_name,
            exception.message.as_deref().unwrap_or("<no message>")
        );

        if let Some(trace) = exception.backtrace() {
            for frame in trace {
                eprintln!("  at {}::{}() in {}:{}",
                    frame.class.as_deref().unwrap_or(""),
                    frame.function.as_deref().unwrap_or("<main>"),
                    frame.file.as_deref().unwrap_or("<internal>"),
                    frame.line
                );
            }
        }
    }
}
```

The backtrace is lazy - only captured when called, so there's zero cost if unused.

### `BacktraceFrame` - Stack Frame Metadata

| Field | Type | Description |
|-------|------|-------------|
| `function` | `Option<String>` | Function name (None for main script) |
| `class` | `Option<String>` | Class name for method calls |
| `file` | `Option<String>` | Source file |
| `line` | `u32` | Line number |

## Zend Extension Handler

For low-level engine hooks beyond the Observer API -- per-statement profiling,
bytecode instrumentation, or `op_array` lifecycle tracking -- register a
`ZendExtensionHandler`. This registers your extension as a `zend_extension`
alongside the regular PHP extension, the same mechanism used by OPcache,
Xdebug, and dd-trace-php.

```rust,ignore
use ext_php_rs::prelude::*;
use ext_php_rs::ffi::zend_op_array;
use ext_php_rs::zend::ExecuteData;
use std::sync::atomic::{AtomicU64, Ordering};

struct StatementProfiler { count: AtomicU64 }

impl ZendExtensionHandler for StatementProfiler {
    fn on_statement(&self, _execute_data: &ExecuteData) {
        self.count.fetch_add(1, Ordering::Relaxed);
    }
    fn on_activate(&self) {
        self.count.store(0, Ordering::Relaxed);
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .zend_extension(|| StatementProfiler { count: AtomicU64::new(0) })
        .hook_statements()
        .finish()
}
```

### Opt-in hooks

| Method | Enables | Cost when enabled |
|--------|---------|-------------------|
| `hook_op_array_compile()` | `on_op_array_compiled` | One callback per compiled function |
| `hook_statements()` | `on_statement` | Extra `ZEND_EXT_STMT` opcode on every statement of every compiled script |
| `hook_fcalls()` | `on_fcall_begin` / `on_fcall_end` | Extra `ZEND_EXT_FCALL_BEGIN`/`END` opcodes around every call site |

### Why opt in?

`hook_statements()` and `hook_fcalls()` tell the PHP engine to emit extra
opcodes in every compiled script. Paying that tax by default would slow every
PHP script, even when your profiler doesn't need the data. The builder makes
the trade-off explicit.

`hook_op_array_compile()` has no compile-time cost: PHP's default
`CG(compiler_options)` already includes `ZEND_COMPILE_HANDLE_OP_ARRAY`. Opting
in only registers the dispatcher, so enabling it just adds one callback per
compiled function.

The other hooks -- `on_activate`, `on_deactivate`, `on_message`,
`on_op_array_ctor`, `on_op_array_dtor` -- are always wired when you register
an extension; they don't need opt-in because they're cold-path.

### ZTS note

Flags are re-asserted in `on_activate` so worker threads created after MINIT
get them on their first request. Scripts pre-compiled by opcache before a
thread's first activation may miss hooks -- for full coverage in ZTS with
opcache, load the extension via `zend_extension=...` in `php.ini`.

### Zend Extension vs Observer API

| Feature | Observer API (`FcallObserver`) | Zend Extension (`ZendExtensionHandler`) |
|---------|------|------|
| Function call hooks | `begin` / `end` with return value | `on_fcall_begin` / `on_fcall_end` (legacy) |
| Filtering | `should_observe` (cached per function) | No built-in filtering |
| Statement-level hooks | Not available | `on_statement` |
| Bytecode access | Not available | `on_op_array_compiled`, `on_op_array_ctor`, `on_op_array_dtor` |
| Request lifecycle | Not available | `on_activate` / `on_deactivate` |
| Best for | Function-level profiling, tracing | Statement-level profiling, code coverage, bytecode instrumentation |

Both can be registered on the same module simultaneously.

## Using All Observers

You can register all observers on the same module:

```rust,ignore
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .fcall_observer(MyProfiler::new)
        .error_observer(MyErrorTracker::new)
        .exception_observer(MyExceptionTracker::new)
        .zend_extension(MyStatementProfiler::new)
        .hook_statements()
        .finish()
}
```

## Thread Safety

Observers are created once during MINIT and stored as global singletons.
They must implement `Send + Sync` because:

- **NTS**: A single instance handles all requests
- **ZTS**: The same instance may be called from different threads

Use thread-safe primitives like `AtomicU64`, `Mutex`, or `RwLock` for mutable state.

## Best Practices

1. **Keep observers lightweight**: Observer methods are called frequently.
   Avoid heavy computations or I/O.

2. **Use filtering wisely**: `should_observe` results are cached for fcall observers.
   For error observers, filter early to avoid unnecessary processing.

3. **Handle errors gracefully**: Don't panic in observer methods.

4. **Consider memory usage**: Implement limits or periodic flushing to avoid
   unbounded memory growth.

5. **Use lazy backtrace**: Only call `backtrace()` when needed. Both `ErrorInfo`
   and `ExceptionInfo` support lazy backtrace capture.

## Limitations

- Only one fcall observer can be registered per extension
- Only one error observer can be registered per extension
- Only one exception observer can be registered per extension
- Only one zend extension handler can be registered per extension
- Observers and handlers are registered globally for the entire PHP process