0

Is there a reasonable way to ensure that you aren't unnecessarily re-instantiating expensive object instances in PHP?

I have an application that deal with US States. Each state is an instance of the USState class. I'd like to ensure that the application only ever has one instance of each state object, although they are used in many places throughout the application.

I looked into the singleton pattern, but that seems to be used for times when a class only has a single instance - here there are 50 instances, but no more.

I guess I could put them in the global scope and always refer to them that way (global $california), but that seems wrong.

1
  • Maybe a Registry or Object Pool. Commented Mar 29, 2017 at 17:01

1 Answer 1

1

I would use Service Locator Pattern or Dependency Injection, which is provided by your framework. Usually I go with Zend Framework, but not knowing your circumstances, I assume you have no framework at all. In this case I would suggest very simple Dependency Injection Container, but that would add a dependency on DIC itself. Pimple is one of them.

Sign up to request clarification or add additional context in comments.

1 Comment

It's a WordPress site with this state stuff grafted on (the states are not custom post types and use a different database table that isn't accessible from the CMS). Adding dependencies is not an issue, it didn't seem like Pimple was meant for cases like this. I'll give it a closer look -- thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.