Skip to content

declaring interfaces using traitsΒ #172

@ju1ius

Description

@ju1ius

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 !

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions