Having created a class that's capable of loading other classes via its static "load()" method, it's time to use it, right? To do so, below I coded another script that utilizes this loader module to eagerly include the previous "User" class. Now, study the following code fragment: try { // load eagerly 'User' class Loader::load('user'); /* rest of logic goes here */ // create instance of 'User' class $user = new User('Mary', 'Smith', 'mary@domain.com'); echo $user; } catch (FileNotFoundException $e){ echo $e->getMessage(); exit(); }
catch (ClassNotFoundException $e){ echo $e->getMessage(); exit(); } Here you have it. Through a few lines of strict object-based code it was feasible to successfully apply the eager loading pattern. As seen above, a couple of "catch()" blocks are used to intercept specific exceptions that might arise when including the file that contains the "User" class, but of course it's possible to remove this error handling mechanism if you don't want to deal with it. Finally, I encourage you to edit all the code samples shown in this tutorial, so you can arm yourself with a better understanding of the eager loading pattern in PHP 5. Final thoughts In this second chapter of the series, I showed how to implement the eager loading pattern in PHP 5 by using a stricter object-based approach. The example that you saw a few lines ago applied this pattern to include a user-related class and create an instance of it without receiving an explicit request to do so, which show that the benefits of using this or any other pattern depend strongly on the development context. In the upcoming article, I'm going to explain how to apply the lazy loading pattern with the same "User" class. Thus, if you wish to learn the full details of this process, then don't miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|