Skip to content

Commit

Permalink
Refactor and simplify README.md
Browse files Browse the repository at this point in the history
Streamlined content for clarity and conciseness. Removed security considerations, advanced usage, and extensive API reference sections. Simplified configuration instructions and emphasized basic usage and installation steps. Updated features and recommendations to be more succinct.
  • Loading branch information
koriym committed Nov 5, 2024
1 parent aa024ab commit 1837515
Showing 1 changed file with 23 additions and 165 deletions.
188 changes: 23 additions & 165 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@ Low-level PHP extension that provides core method interception functionality for

## Features

- Method interception with comprehensive parameter access and return value modification
- Efficient low-level method interception
- Support for intercepting final classes and methods
- Full parameter and return value modification support
- Works seamlessly with the `new` keyword
- Thread-safe operation support in ZTS builds
- Debug mode with configurable levels
- Memory-efficient interception handling
- Thread-safe operation support

## Requirements

- PHP 8.1 or higher
- Linux, macOS, or Windows with appropriate build tools
- Thread-safe PHP build recommended for production use
- Thread-safe PHP build recommended for multi-threaded environments

## Installation

Expand All @@ -37,48 +36,25 @@ make
make install
```

3. Add the following configuration to your php.ini file:
3. Add the following line to your php.ini file:
```ini
; Required extension loading
extension=rayaop.so # For Unix/Linux
extension=rayaop.dll # For Windows

; Optional configuration
[rayaop]
rayaop.debug_level = 0 ; 0=disabled, 1=basic, 2=verbose
```

4. Verify installation:
```bash
php -m | grep rayaop
```

## Security Considerations

### Thread Safety
The extension is designed to be thread-safe and includes proper locking mechanisms for global state. When using in a threaded environment (e.g., with PHP-FPM), ensure you're using the Thread-Safe (ZTS) version of PHP.

### Memory Management
- The extension implements careful memory management with proper allocation and deallocation
- Includes protection against memory leaks in interceptor chains
- Implements safeguards against infinite recursion
- Uses secure hash table operations for interceptor storage

### Best Practices
1. Always validate interceptor objects before registration
2. Implement proper error handling in interceptors
3. Avoid storing sensitive data in interceptor instances
4. Set appropriate memory and recursion limits in production

## Design Decisions

This extension provides minimal, high-performance method interception capabilities:

- One interceptor per method: The extension supports a single active interceptor per method, with the last registered interceptor taking precedence
- Final class support: Can intercept final classes and methods, unlike pure PHP implementations
- Raw interception: No built-in matching or conditions (use Ray.Aop for these features)
- Thread-safe design: All global state is properly protected
- Zero-copy parameter passing where possible
- Thread-safe: Safe to use in multi-threaded environments like PHP-FPM

## Relationship with Ray.Aop

Expand All @@ -93,132 +69,37 @@ Ray.Aop provides:
When both are used together:
- Ray.Aop handles the high-level AOP logic
- This extension provides the low-level interception mechanism
- Ray.Aop automatically utilizes this extension when available for better performance

## Advanced Usage
## Basic Usage

### Error Handling
### Simple Interceptor
```php
class ErrorHandlingInterceptor implements Ray\Aop\MethodInterceptorInterface
class LoggingInterceptor implements Ray\Aop\MethodInterceptorInterface
{
public function intercept(object $object, string $method, array $params): mixed
{
try {
return $object->$method(...$params);
} catch (Throwable $e) {
// Handle or transform the error
throw new CustomException("Error in {$method}: " . $e->getMessage());
}
echo "Before {$method}\n";
$result = $object->$method(...$params);
echo "After {$method}\n";
return $result;
}
}
```

### Parameter Modification
```php
class ParamValidatorInterceptor implements Ray\Aop\MethodInterceptorInterface
{
public function intercept(object $object, string $method, array $params): mixed
{
// Validate and potentially modify parameters
$sanitizedParams = array_map(
fn($param) => is_string($param) ? htmlspecialchars($param) : $param,
$params
);

return $object->$method(...$sanitizedParams);
}
}
// Register the interceptor
method_intercept(TestClass::class, 'testMethod', new LoggingInterceptor());
```

## API Reference

### Core Functions

#### method_intercept()
```php
bool method_intercept(string $class_name, string $method_name, object $interceptor)
```
Registers an interceptor for a specific class method. Only one interceptor can be active per method - registering a new one will replace any existing interceptor.
- **Parameters:**
- `$class_name`: Fully qualified class name to intercept
- `$method_name`: Name of the method to intercept
- `$interceptor`: Object implementing Ray\Aop\MethodInterceptorInterface
- **Returns:** bool - True on successful registration, False if registration fails
- **Errors:** May generate E_WARNING on invalid handlers or memory allocation failures

#### method_intercept_init()
```php
bool method_intercept_init()
```
Initializes or resets the interception system. Cleans up any existing interceptors and reinitializes the interceptor storage.
- **Returns:** bool - True if initialization succeeds, False if memory allocation fails
- **Errors:** May generate E_ERROR on memory allocation failures

#### method_intercept_enable()
```php
void method_intercept_enable(bool $enable)
```
Enables or disables the method interception system globally. When disabled, intercepted methods will execute normally.
- **Parameters:**
- `$enable`: True to enable the interception system, False to disable it
- **Note:** Disabling interception does not remove registered interceptors

### Basic Configuration Example
### Method Interception Setup
```php
// Initialize the interception system
method_intercept_init();

// Enable method interception
method_intercept_enable(true);

// Register an interceptor
$result = method_intercept(
MyClass::class,
'targetMethod',
new MyInterceptor()
);

if (!$result) {
// Handle registration failure
}
```

## Performance Considerations

### Memory Usage
- Each interceptor registration uses approximately 200 bytes of memory
- The extension maintains a hash table for quick interceptor lookups
- Memory usage scales linearly with the number of intercepted methods

### Performance Considerations
- Method interception adds some overhead to each method call
- The extension implements efficient parameter handling
- Interceptor lookup is optimized using hash tables
- Execution depth is tracked to prevent infinite recursion


## Troubleshooting

### Common Issues

1. Segmentation Faults
- Ensure Thread-Safe PHP in multi-threaded environments
- Check memory limits and recursion depth
- Verify interceptor object validity

2. Memory Leaks
- Implement proper cleanup in interceptors
- Use method_intercept_init() when necessary
- Monitor memory usage with debug_level = 1

3. Performance Issues
- Review interceptor complexity
- Check recursion depth settings
- Monitor interception patterns

### Debug Mode
Enable debug mode for detailed logging:
```ini
rayaop.debug_level = 2
// Register interceptors
method_intercept(MyClass::class, 'myMethod', new MyInterceptor());
```

## Development
Expand All @@ -242,35 +123,12 @@ For specific tests:
make test TESTS="-v tests/your_specific_test.phpt"
```

### Debug Builds
```bash
./configure --enable-debug
make clean
make
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Add appropriate tests for your changes
4. Ensure all tests pass (`make test`)
5. Run memory leak checks (`make test TESTS="-m")
6. Commit your changes
7. Push to the branch
8. Create a Pull Request

## Support and Feedback

- Issues: Report bugs via GitHub Issues
- Questions: Use GitHub Discussions
- Security: Report security issues directly to maintainers
- Performance: Share benchmarks and optimization suggestions

## License

[MIT License](LICENSE)

## Credits
## Author

Akihito Koriyama

- Akihito Koriyama
This extension was developed with the assistance of AI pair programming, which helped navigate the complexities of PHP extension development and PECL standards.

0 comments on commit 1837515

Please sign in to comment.