jexx2345
jexx2345

Reputation: 678

Common object shared across many other classes

I am currently refactoring an application into multiple classes in an attempt to fulfill Single Responsibility Principle; however, many methods in the original mammoth classes use one common "metadata" object (bound as a class property) for their business logic.

For example:

if($this->metadata->applyTracking) {
 // perform tracking logic
}

When I am separating these classes out, I am considering two options:

  1. Passing this object to particular methods of the class, on case by case basis (Can be many occurences).
  2. Adding this object as class properties (Many classes will have this property injected).
  3. Making the object as a Singleton (I am wary of this approach since it may share the same fallbacks as globals)

Any advice on which path to take?

Upvotes: 1

Views: 372

Answers (3)

quickshiftin
quickshiftin

Reputation: 69621

If you have inheritance in your code you may consider assigning it as a member in base classes and exposing the instance as a protected variable.

The Singleton really is more about whether or not the class is supposed to have only one instance in memory at a time, or if you will be instantiating the class many times.

Upvotes: 1

David Myers
David Myers

Reputation: 799

It's hard to say for sure without knowing more about the how the object is being used, but I would probably suggest having a base class which defines the needed properties and then just inheriting that base class in any subsequent classes which need access to those properties.

quickshiftin just beat me to the punch though, haha.

Upvotes: 0

Kenaniah
Kenaniah

Reputation: 5201

Method #2 seems to be best. I would inject an object repository, in which each member of the repository would be a different object that provides a different service. An example class can be found here: https://github.com/kenaniah/insight/blob/master/classes/registry.php

Upvotes: 1

Related Questions