Pete
Pete

Reputation: 7579

Grouping/encapsulating related functions that are across multiple php files

I'm working on an app, and part of functionality of this app is that it is extendable through addons.

The main app uses has a Render class that contains a lot of static methods that have to do with output. The actual methods interact with models/views, but the basic idea is that the Render class encapsulates methods that render something, like:

// To output "hello"
Render::sayHello();

// To output a picture of a cat wearing a hat
Render::catWithHat();

Now, from time to time addons require their own unique output functions. These output functions are very similar to the Render methods. So...

My first thought was that it would be great if I could dynamically add methods to the Render class, but after reading up about on-the-fly method creation it sounds like that's generally not considered very good practice.

So then I thought, well, I could just not encapsulate the addons' render functions at all. So that you'd just call them like:

renderMyAddonOutput();

I don't love that idea either, though.

So I guess I'm just wondering what would be considered best practice for encapsulating related functions that are declared across a variety of files.

Thoughts?

Note: if it makes any difference, I'm using Laravel for this (the very latest version).

Upvotes: 1

Views: 67

Answers (1)

Seb Barre
Seb Barre

Reputation: 1647

I would consider using a Plugin pattern where an add-on registers itself into some kind of static container on init, and then you can use PHP's magic method __call() or __callStatic() to check the plugin array when a method is called that isn't found in the base class..

So if you had:

Render::pluginMethod()

then __callStatic() would check your plugin registry (which can be as simple as a static array of plugin classes or methods) and if it finds that method, it calls/returns it.

Upvotes: 1

Related Questions