Home arrow PHP arrow PHP Proxy Patterns: Completing a Blog

PHP Proxy Patterns: Completing a Blog

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

While proxy objects can be utilized in a variety of situations and environments, they yield excellent results when lazy-loading data from an applicationís persistence layer (usually this layer is seated upon a RDBMS, but it could be a web service or anything else). With the progressive adoption in the PHP field of Domain-Driven Design methodologies, the use of proxies for loading and reconstituting collections of domain objects on request from the underlying storage can help in the implementation of more efficient persistence strategies. This is true despite the need in some cases to create a few additional abstraction layers, like data mappers, repositories and even services.

It's relatively easy to use the capabilities of proxies and lazy-load sets of entities from a database, even in the most simple use cases. Indeed, in the two previous parts of this tutorial, I started building an extendable blog program. It used a couple of proxy classes to pull, from a MySQL table, the comments related to a particular blog entry.

Unfortunately, the blog in its current state isnít entirely functional. It's necessary to add to it a simple service layer. With this layer, all of the logic required by the interaction between the mappers and the database can be neatly encapsulated behind a cleaner and uncluttered API. In this final installment, Iíll set up this additional layer, thus finishing the sample blog program.

Now, itís time to continue learning how to make proxy objects work for us in PHP. Letís jump in!

Adding a service layer to the blog

In reality, adding a service layer to the blogís existing structure is optional, as itís possible to demonstrate the functionality of proxies without implementing this extra abstraction tier. However, since I want to keep all the logic required to perform CRUD operations on blog entries hidden behind a single entry point, accessible to different front-ends, Iíll be bold and bring this layer to life anyway.

Having said that, this is the class that will make the service work. Take a close look at it:   

(MyApp/Service/EntryService.php)

<?php

namespace MyApp\Service;
use MyApp\Model\Mapper,
    MyApp\Model;

class EntryService
{
    protected $_entryMapper;
   
    /**
     * Constructor
     */
    public function __construct(Mapper\EntryMapper $entryMapper)
    {
        $this->_entryMapper = $entryMapper;
    }
   
    /**
     * Get the entry mapper
     */
    public function getEntryMapper()
    {
        return $this->_entryMapper;
    }
   
    /**
     * Find an entry by its ID
     */ 
    public function findById($id)
    {
        return $this->_entryMapper->findById($id);  
    }
   
    /**
     * Find entries according to the given criteria
     */
    public function find($criteria = '')
    {
        return $this->_entryMapper->find($criteria);
    }
   
    /**
     * Insert a new entry
     */
    public function insert(Model\Entry $entry)
    {
        return $this->_entryMapper->insert($entry);
    }
   
    /**
     * Delete an existing entry
     */
    public function delete($id)
    {
        return $this->_entryMapper->delete($id);
    }                 
}

As you can see above, this new class is a basic wrapper for the previous entry mapper, which can fetch, save, and remove entries from the database. At first glance, it looks like a repository; it can deal with aggregate roots (the blog entries). Keep in mind, however, that it can be easily extended to perform many other tasks with the involved domain objects, such as representing them in XML, emailing them, or whatever comes to mind.

If you understand how the service works, the next step is to create a simple dependency injection container (DIC). This container will take care of spawning (in this case manually) the serviceís object graph in a snap. To do this, Iíll make the container an implementer of the following interface:
 
(MyApp/Service/InjectorInterface.php)

<?php

namespace MyApp\Service;

interface InjectorInterface
{
    public function create(); 
}

That was simple to code and read, right? So, move on and take a look at the originating class of the aforementioned DIC:

(MyApp/Service/EntryServiceInjector.php)

<?php

namespace MyApp\Service;

use MyApp\Model\Mapper,
    MyApp\Library\Database;

class EntryServiceInjector implements InjectorInterface
{
    protected $_entryService;
   
     /**
     * Create the entry service
     */
    public function create()
    {
        if ($this->_entryService === null) {
            $mysqlAdapter = new Database\MysqlAdapter(array(
                'host',
                'user',
                'password',
                'database'
            ));
            $this->_entryService = new EntryService(
                new Mapper\EntryMapper($mysqlAdapter, new Mapper\CommentMapper($mysqlAdapter))
            );
        }
        return $this->_entryService;
    }  
}

As the above code fragment shows, the ďEntryServiceInjectorĒ class's responsibility is to build the graph corresponding to the previous entry service. As I said before, in this case all the dependencies are injected manually; even so, implementing this DIC helps to separate object instantiation from application logic, which is a good programming practice.

So far, so good. At this point, the blogís service layer is finally ready for some real action. However, thereís one more thing that Iíd like to do. Since the blog might be coupled with an existing MVC stack (for instance, the infrastructure provided by a framework from the many available out there), itíd be helpful to create a basic helper. This helper would allow you to create the service on request, and can be consumed easily within an action controller.

The helper's definition will be shown in the next section.



 
 
>>> 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: