Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of this circular dependency?

I am currently writing a few classes to deal with localization in a PHP web application.

The classes are:

  • Locale - Deals with setting and getting the user's locale, timezone, language.
  • LocaleFormat - Deals with formatting dates, collations, currency formats, etc.
  • Timezone - Deals with compiling a list of time zones for countries and other functions related to timezones.
  • LocaleData - Fetches locale data, for example address formats and things like post code regexes.

The whole application works properly, but I need to add a few more things to Timezone.

This results in this problem: Locale requires Timezone's methods which requires LocaleData's methods which requires Locale's methods.

How can I break this circular dependency? Should I break my classes down into smaller pieces? Are there any patterns for dealing with this?

Cheers :)

like image 529
F21 Avatar asked Sep 17 '11 06:09

F21


1 Answers

If you are only calling methods from other classes, load all the classes first, then you can call the methods between the classes. Don't perform any initialization within the class files, that should be done in a separate "loader" file that "includes" the files, then calls the does initialization.

If you are getting circular dependencies based on classes extending other classes, then you need to rethink the whole setup.

like image 148
Brent Baisley Avatar answered Oct 18 '22 11:10

Brent Baisley