Home arrow PHP arrow Page 2 - PHP Service Layers: A Final Example

The service in action: fetching user entities from storage - PHP

If you’re looking for an approachable guide that teaches you how to implement an easily-customizable service layer in PHP, then take a peek at this article series. In a step-by-step fashion, it walks you through the development of a sample web application, which uses a service to perform CRUD operations on a domain model composed of a few user entities.

TABLE OF CONTENTS:
  1. PHP Service Layers: A Final Example
  2. The service in action: fetching user entities from
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
October 17, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To demonstrate how to work with the previous user service in a concrete situation, I’ll be utilizing the following “users” MySQL table. It already contains a couple of trivial rows. Take a look at it: 

Admittedly, the above table isn’t the most complex one that you’ll see in your lifetime, but it's good enough for demonstration purposes. Now, say that you need to fetch the above table records by means of the pertinent service. In a case like this, you could use a script similar to the following:   

(index.php)

<?php

use MyApplicationLoaderAutoloader as Autoloader,
    MyApplicationServiceServiceLocator as ServiceLocator,
    MyApplicationInjectorUserServiceInjector as UserServiceInjector;

// include the autoloader
require_once 'Loader/Autoloader.php';
Autoloader::getInstance();

//add the user service injector to the service locator
ServiceLocator::addInjector('user', new UserServiceInjector);

// create an instance of the user service via the associated injector
$userService = ServiceLocator::getService('user');

// fetch a single user from the persistence layer and display their data
$user = $userService->findById(1);
echo $user->fname . ' ' . $user->lname . ' ' . $user->email;

/*

displays the following

Alex Gervasio alex@domain.com

*/

// fetch all users from the persistence layer and display their data
$users = $userService->findAll();
foreach($users as $user) {
    echo $user->fname . ' ' . $user->lname . ' ' . $user->email . '<br />';}

 

/*

displays the following

Sandra Smith sandra@domain.com
Alex Gervasio alex@domain.com

*/

As seen above, once an instance of the service is grabbed via the service locator helper, it’s used to retrieve all the records present in the previous “users” table via the “findById()” and “findAll()” methods. This shows how easy it is to put the service into action, and how it permits you to interact with different clients without having to modify the infrastructure of an application.

 

In addition, you may have noticed that the service is created by using its associated dependency injection container. This is added to the service locator in the following line:

//add the user service injector to the service locator
ServiceLocator::addInjector('user', new UserServiceInjector);

In this case, this was done within the same script that fetches the database records (and that in turn reconstitutes the corresponding user entities); nevertheless, in production environments, all of the initialization tasks, such as injecting DI containers or creating a database adapter, should be performed in a separate bootstrap file or class. Keep this in mind when developing your MVC applications, and you’ll save yourself from many maintenance headaches.

And now that you've seen how simple it is employ this sample service to retrieve some user objects via a couple of generic finders, it’s time to show how to use it to add a new user to the database and delete an existing one.     

Creating a final example: saving, removing domain objects and more

In fact, saving and removing users from the earlier MySQL table via the service layer is a simple process. Of course, the best way to prove this is by example. Below, I coded one for you that performs these tasks in a comprehensive manner:

(index.php)

<?php

use MyApplicationLoaderAutoloader as Autoloader,
    MyApplicationServiceServiceLocator as ServiceLocator,
    MyApplicationInjectorUserServiceInjector as UserServiceInjector;

// include the autoloader
require_once 'Loader/Autoloader.php';
Autoloader::getInstance();

//add the user service injector to the service locator
ServiceLocator::addInjector('user', new UserServiceInjector);

// create an instance of the user service via the associated injector
$userService = ServiceLocator::getService('user');

// insert a new user into the persistence layer
$user = new MyApplicationEntityUser(array(
    'fname' => 'Jennifer',
    'lname' => 'Smith',
    'email' => 'jennifer@domain.com'
));
$userService->insert($user);

// remove a user from the persistence layer
$userService->delete(1);

As the above code snippet shows, inserting a new user into the storage and deleting an existing one is reduced to calling the service’s “insert()” and “delete()” methods, and nothing else. If you wan tot see how to fetch all current users in XML, the example below should answer your questions:

(index.php)

<?php

use MyApplicationLoaderAutoloader as Autoloader,
    MyApplicationServiceServiceLocator as ServiceLocator,
    MyApplicationInjectorUserServiceInjector as UserServiceInjector;

// include the autoloader
require_once 'Loader/Autoloader.php';
Autoloader::getInstance();

//add the user service injector to the service locator
ServiceLocator::addInjector('user', new UserServiceInjector);

// create an instance of the user service via the associated injector
$userService = ServiceLocator::getService('user');


// fetch all users in XML format
header('Content-type: text/xml');
echo $userService->toXML();

There you have it. This example effectively shows how to use the service for performing a variety of tasks, and not merely running CRUD functions on domain objects. It also demonstrates how easy it is to call it from different client layers (for instance, from within an action controller or even directly from a view).

Naturally, this doesn’t imply that you should use a service in every possible situation. However, its intrinsic flexibility turns it into a hard-to-beat contender, especially when developing medium/large-scale applications that need to be interfaced with multiple clients. So, keep the pattern at hand in your developer’s toolbox. Who knows? Maybe you’ll need to use it sooner than you think.  

Final Thoughts

Finally, we’ve come to the end of this series. You've learned how to implement a functional and easily customizable service layer. As I just noted, the construction of a service isn’t something that you need to face in every use case. That's especially true in the PHP field, where Domain-Driven Design is still in its infancy (even though it’s moving forward quickly).

Despite this, as PHP applications grow in complexity and size, sooner or later you’ll need to create a flexible structure that permits you to extend their functionality or even migrate them to a different framework. In those cases, you’ll love having a service layer at your disposal, take my word for it.

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: