Question

If one uses autoloader function (with spl_autoload_register), does one need anymore:

  • singleton: all needed classes will be loaded by autoloader anyway, including database, logs, r&r, fronts etc. so need for "always on" etc. object is not clear to me
  • factory: again, autoloader will load required class, so is there a point to use factory class to instantiate worker classes implementing interface, or extending abstract class
Was it helpful?

Solution

A singleton is used to hold a single instance of a particular class, so that whenever the instance is retrieved it will always be the same. Therefore, setting data will mean that the data is always the same when retrieving it.

This is different from auto loading a class, as each time you create a new instance you reset the state to the class' default. Still, Singletons should be used sparingly, as they are essentially glorified global variables.

A factory pattern should be used to delegate the determination and creation of objects. It's used when you don't want to specify a concrete class, but require a certain sub-class under a set of conditions. You can't pass construction parameters to an autoloader, and some complex logic may be required to work out which object should be returned from a factory, so again it doesn't achieve the same thing.

An autoloader should just be used to find a class file and include it. It shouldn't (and can't) do any logic such as instantiating an object or making decisions about which object to load.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top