Now that you've grasped the underlying logic of using late static bindings with the prior registry classes, it’s time to build an example that demonstrates whether they're as functional as they look. With that idea in mind, below I coded a script that shows how to use an instance of the “ArrayRegistry” class to save and fetch some fictional users from RAM. Here it is:
// include source classes
// grab the Singleton instance of the ArrayRegistry
$arrayRegistry = ArrayRegistry::getInstance();
// save some users to the registry
$arrayRegistry->set('user1', 'Julie Smith')->set('user2', 'Mary Wilson');
// get the first user from the registry
displays the following
catch (Exception $e)
That was a breeze to code, wasn’t it? As you could see above, using the array registry class is a extremely simple process that doesn’t bear any further discussion. I want you to pay attention to the line that grabs the Singleton instance of the registry via the “getInstance()” method, since it shows in a nutshell the real functionality of late static bindings.
Prior to PHP 5.3, this method should have been implemented directly within the concrete registry. But now, it lives comfortably inside the parent, thus making it possible to share it with multiple registry subclasses.
So far, so good. At this point the example illustrates that LSB is really a powerful feature that can be used, among other things, to create a hierarchy of registry classes. But as you may have noticed, the example starts manually including the source classes. This is pretty annoying, considering the nice autoloading capabilities that PHP hides under the hood. Therefore, in the last section I’m going to enhance the earlier example by adding to it a simple autoloader class.
To see how this autoloader will be defined, jump forward and read the following segment. It’s only one click away.
blog comments powered by Disqus