-
Notifications
You must be signed in to change notification settings - Fork 16
Loader and name lookup
The library comes with its own class loader, \FACTFinder\Loader in file src/FACTFinder/Loader.php. It's really just a static collection of methods, but if you load this file first, the Loader takes care of all further class loading within the library for you.
It is useful to create a shorthand alias for the Loader, because you are potentially going to use it a lot. So start all FACT-Finder related files with
use \FACTFinder\Loader as FF;
The remaining code on this page assumes you did that.
The Loader provides three useful static methods: getInstance, getClassName, isInstanceOf. Each one requires a class identifier. A class's identifier is simply it's fully qualified name without the \FACTFinder namespace (and no leading backslash). In each case, this name is first resolved to an actual class (see further down for how name lookup works), and further processed:
-
getInstanceinstantiates the class passede in as the first argument (who knew!) - it takes constructor arguments after the class identifier. -
getClassNamesimply returns the fully qualified class name for an identifier. This is useful if you want to call static methods on the class. -
isInstanceOftakes and object and a class identifier, and checks if the object is an instance of the resolved class. Use this instead ofinstanceoforis_a()when dealing with library functions, because you may not know which implementation is actually being used for a particular class.
The Loader looks for the class in three places in the following order:
- in the
\FACTFinder\Customnamespace - in the
\FACTFindernamespace - in the root namespace
Say you do something like
FF::getInstance(`Some\Namespace\MyClass`, $constructorArgument);
The Loader will try to find the following the classes and instantiate the first one it finds:
\FACTFinder\Custom\Some\Namespace\MyClass\FACTFinder\Some\Namespace\MyClass\Some\Namespace\MyClass
It expects those to be found in a file structure that mirrors the namespaces.
Obviously, the class it will usually find is the second one. That is, you will call something like FF::getInstance('Core\XmlConfiguration'); and expect \FACTFinder\Core\XmlConfiguration to be instantiated. The first and third possibilities have the following implications:
- You can overwrite any library class (except the Loader itself) by creating a class of the same name within the
\FACTFinder\Customnamespace. Because the Loader is used consistently within the library, everything will use your implementation instead. However, we recommend that you also inherit from the class you overwrite - there are some type hints in the code which may break if you just use a completely unrelated class. - You can also use the Loader to instantiate any other class that is not even part of the library, as long as your overall project structure is in 1:1 correspondence with the namespace structure.