Allenph Allenph - 1 year ago 45
PHP Question

Is it acceptable to create a static factory method on a class?

I have a class whose instances are an object representing messages in a standardized format. These instances are eventually output as a JSON object so that they can be transferred between processes.

The class has some very helpful methods which I use to validate and control the message without delving into the object structure. This is fine and dandy when I'm creating the message and sending it out, but when I receive the JSON object it contains only data, and none of these helpful methods.

What is the best way to map these incoming JSON objects to a class instance?

I can think of four ways...

1) Add a static method to the class which accepts a JSON string and produces a new instance of the class.

2) Add a method to the class which accepts a JSON string and maps the JSON object to that instance.

3) Have an optional argument in the constructor which accepts a JSON string and maps it to the instance on construction.

4) Turn the class into a service with a factory method.


I would love to do 3, but the problem is that I cannot return feedback if the object wasn't correctly formatted, etc.

Answer Source

1) Add a static method to the class which accepts a JSON string and produces a new instance of the class.

This will make the code harder to unit test and scale as features change. See unit testing and Static methods

2) Add a method to the class which accepts a JSON string and maps the JSON object to that instance.

This is a good idea. This could be useful in conjunction with #4. Implementing this alone might become tedious if you want to support multiple objects/JSON formats.

3) Have an optional argument in the constructor which accepts a JSON string and maps it to the instance on construction.

I personally find this to be an awkward use of the constructor. Things like JSON validation would need to throw an exception.

4) Turn the class into a service with a factory method.

Creating a factory is the most extensible way forward. Think down the line if you have multiple JSON formats and objects to map to. This central class would let you choose the correct mappings and handle changes over time. It's also easy to unit test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download