1

I'm creating a PHP library to extract schema.org structured data out of web pages.

Schema.org features a multiple inheritance hierarchy that I can only achieve through PHP interfaces:

interface LocalBusiness extends Organization, Place
{
}

In addition to that, schema.org allows an object to be of multiple independent types, for example it can be both a Book and a Product, and use properties from both:

<!-- Uses both the "Book" and "Product" item types -->
<div vocab="http://schema.org/" resource="#record" typeof="Book Product">
...
<span property="author">
...
<span property="sku">

To support this use case, I need to dynamically generate classes that implement more than one interface. In the example above, this could look like:

new class implements Book, Product
{
  use BookTrait;
  use ProductTrait;
}

I can obviously not generate all interface combinations ahead of time, so I'm thinking of a way to generate such an implementation at runtime.

As far as I know, reflection does not allow to do this kind of things, so the only way I can think of is using generated code and eval(), like mocking libraries do. The problem is, eval() can be disabled, which is an issue when writing a general-purpose library.

Did I overlook something? Is there another way to dynamically create an object that implements an arbitrary number of interfaces, that are only known at runtime?

BenMorel
  • 34,448
  • 50
  • 182
  • 322

0 Answers0