Creating PHP interfaces, traits, and classes dynamically at runtime
PHP is a wonderful dynamic language that's capable of many cool things. I recently stumbled upon something quite fantastic that I want to share with you.
In most projects you'll probably create one class or interface per file.
interface MyInterface
{
}
What is less common is that you can create multiple classes or interfaces per file.
interface MyInterface
{
// implementation
}
interface AnotherInterface
{
// implementation
}
What is even less common is that you can conditionally define an interface. As a bonus, you can conditionally extend another interface 🤯.
if ($condition) {
interface MyInterface
{
// implementation
}
} else {
interface AnotherInterface extends YetAnotherInterface
{
// another implementation
}
}
You can also define traits dynamically. So, depending on certain conditions you can add different methods or other implementations.
if ($condition) {
trait MyTrait
{
// add methods
}
} else {
trait MyTrait
{
// add methods
}
}
If you got here via /r/php and immediately want to join the army of people commenting "YOUR ARCHITECTURE IS BAD", rest assured that I'm not advocating to use this everywhere. Probably this technique is not needed in most projects. It could be handy in a package that needs to stay compatible with multiple versions of a dependency.
I think it's pretty cool that the dynamic nature of PHP allows for this behaviour and makes it possible for people who need it.
What are your thoughts on "Creating PHP interfaces, traits, and classes dynamically at runtime"?