ext-php-rs
ext-php-rs copied to clipboard
declaring interfaces using traits
Hi,
It would be nice to be able to declare interfaces using traits instead of structs, so that the following example would work:
#[php_interface]
pub trait Greeter {
fn greet(&self) -> String;
}
#[php_class]
#[implements(Greeter)]
pub struct Hello(String);
#[php_impl]
impl Hello {
pub fn __construct(subject: String) -> Self { Self(subject) }
}
#[php_impl]
impl Greeter for Hello {
pub fn greet(&self) -> String { format!("Hello, {}!", self.0) }
}
<?php
$hello = new Hello('world');
assert($hello instanceof Greeter);
echo $hello->greet();
And it would be even nicer if the interface contract could work across the rust/php borders:
#[php_interface]
pub trait Greeter {
fn greet(&self, subject: String) -> String;
}
#[php_class]
pub struct Greetable(String);
#[php_impl]
impl Greetable {
pub fn __construct(name: String) {
Self(name)
}
pub fn greeted(&self, greeter: impl Greeter) -> String {
greeter.greet(self.0)
}
}
<?php
$hello = new class implements Greeter {
public function greet($subject: string): string {
return "Hello, {$subject}";
}
};
var_dump((new Greetable('world'))->greeted($hello)); // => "Hello, world!"
Thanks for the great work here btw !