Home arrow PHP arrow Page 2 - PHP Proxy Patterns: Completing a Blog

Building a basic service locator - PHP

In this third part of a series on proxy objects, we'll create a simple service layer to add to our blog program. With this finished application, you'll see exactly how proxy objects can be powerful allies when you need to persist the entities of a domain model in a database.

TABLE OF CONTENTS:
  1. PHP Proxy Patterns: Completing a Blog
  2. Building a basic service locator
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
October 31, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

If you want to see how the helper mentioned in the previous section looks, check the following code fragment:

(MyApp/Service/EntryServiceLocator.php)

<?php

namespace MyApp\Service;

class EntryServiceLocator
{
    protected $_entryServiceInjector;
    protected $_entryService;
   
    /**
     * Constructor
     */
    public function __construct(EntryServiceInjector $entryServiceInjector)
    {
        $this->_entryServiceInjector = $entryServiceInjector;
    }
   
    /**
     * Get the entry service injector
     */
    public function getEntryServiceInjector()
    {
        return $this->_entryServiceInjector;
    }
   
    /**
     * Set the entry service
     */
    public function setEntryService(EntryService $entryService)
    {
        $this->_entryService = $entryService;
    }
   
    /**
     * Get the entry service (if not set already, the service is created via the related injector)
     */
    public function getEntryService()
    {
        if ($this->_entryService === null) {
            $this->_entryService = $this->_entryServiceInjector->create();
            if (!$this->_entryService instanceof EntryService) {
                throw new \RunTimeException('Unable to create the entry service.');
            }
        }
        return $this->_entryService;
    }      
}

As shown above, this helper class is a very basic service locator. It allows you to inject and create, via the associated DIC, an instance of the blog entry service that you saw before. In a typical situation, this locator should be initialized in a bootstrap class or something like that, so that it could be used by any action controller, based on a specific request. For the sake of brevity, though, the details of how to accomplish this will be left as homework for you. If you feel adventurous, you can integrate this helper (or a similar one) into your existing framework.

So far, so good. With this service locator ready to go, it’s finally time to give the blog a shot and see if its proxy classes are as functional as they look. However, this testing process will be conducted in the following section. 

Taking the final step: seeing the blog in action

To test the blog, I'm going to create a hypothetical scenario where there are a few blog entries posted by myself, which have been commented upon by some insightful users. To do this, I’ll be using the following “entries” and “comments” MySQL tables, which have been populated with the following data:

As the tables show, I’m rather lazy and not very chatty when posting; even so, some people did take some time to comment on my short posts, which is quite remarkable.

However, the important part of this fictional example is that it demonstrates how to pull my posts from the corresponding table and load the related comments on request. The following script does that (as usual, the implementation of the autoloader has been omitted to keep the code shorter and easier to read):     

(index.php)

<?php

use \MyApp\Library\Loader\Autoloader as Autoloader,
    \MyApp\Service\EntryServiceLocator as EntryServiceLocator,
    \MyApp\Service\EntryServiceInjector as EntryServiceInjector,
    \MyApp\Views\View as View,
    \MyApp\Model\Entry as Entry;

require_once __DIR__ . '/Library/Loader/Autoloader.php';

// create an instance of the autoloader
$autoloader = new Autoloader;

// create an instance of the entry service locator
$entryServiceLocator = new EntryServiceLocator(new EntryServiceInjector);

// get the entry service (created by the related injector)
$entryService = $entryServiceLocator->getEntryService();

// fetch all the entries from the storage
$entries = $entryService->find();

// create a view and assign to it the entries
$view = new View(array('templateFile' => 'entries.php'));
$view->header = 'Using the proxy pattern in PHP';
$view->entries = $entries;

// display the entries (the related comments are lazy-loaded)
echo $view->render();

As the above script shows, once an instance of the entry service is created via the associated injector, the object is used for fetching blog entries from the database. Then, they’re assigned to a view, which is finally rendered on screen by means of the corresponding template file.

As you’ll possibly recall, this file first echoes the blog entries, which is the expected behavior; however, the comments are initially filled in with a proxy object, and are only retrieved when the proxy is used in a “foreach” loop. The result of this process can be seen more clearly in the following image:    

Not bad at all, right? This shows in a nutshell the functionality of proxies for lazy-loading data -- in this case, a bunch of domain objects. If you’re wondering how to add new blog entries or delete an existing one using the previous script, take a look: 

// add a new entry to the storage
$entry = new Entry(array(
    'title'   => 'This is a sample entry',
    'author'  => 'Lisa Williams',
    'content' => 'This is the content of the sample entry.'
));

$entryService->insert($entry);

// delete an existing entry from the storage
$entryService->delete(1);

Mission accomplished. At this stage, you should have a spot-on idea of how to use proxy objects for loading entities from a database on request. Of course, the implementation of my own lazy-loading proxies may be more complex than usual, as they have to interact with a mapping layer. Nevertheless, if you don’t use data mappers to fetch domain objects from your persistence layers, the construction of such proxies might be much simpler.

Final Thoughts

We’ve come to the end of this tutorial. Hopefully, you found it an educational journey, as you learned  how proxy objects can be powerful allies when you need to persist in a database the entities of a domain model. While in this case, the model was inherently anemic (after all, blog entries and comment objects are usually simple data holders that don’t carry much behavior per se), the example demonstrated how to exploit the functionality of proxies to implement more efficient data persistence strategies.  

As I said at the beginning, proxies can be used in several situations, and for many purposes. So, make sure that you grasp their driving logic, as this will help you get the most out of them when developing your own object-oriented applications.

See you in the next PHP tutorial!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: