Home arrow PHP arrow PHP: Modeling a URL Class

PHP: Modeling a URL Class

In this first part of a series, you'll get an overview of what the Object Value pattern is and how to implement it in PHP. Specifically, in this part you'll learn how to define a basic URL class that can be used to easily create immutable value objects.

TABLE OF CONTENTS:
  1. PHP: Modeling a URL Class
  2. Adding getters to the Url class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
November 01, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

While itís fair to admit that PHP isnít exactly the most elegant and efficient language that you can use for developing object-oriented applications, its improved object model packs in enough functionality to implement the OOP paradigm in a pretty thorough fashion. This  becomes particularly evident in the new methodologies that numerous PHP programmers are starting to adopt or already utilize for building web-based programs -- especially when looking back to the old days when nearly every dynamic web page was generated through tons of transcription scripts.

Today, many developers appeal to the functionality of design patterns and other trusted approaches to solve software-related problems with elegance and efficiency. Whatís more, things like Factories, Entities, Services and Repositories, just to name a few, have become familiar, as more and more programmers enter the terrain of domain-driven design (DDD). Granted, DDD in PHP is still in its infancy, particularly when compared to older and more mature languages like Java.   

This doesnít mean, however, that the implementation of certain patterns extremely relevant in DDD is pointless. Not at all, trust me. To demonstrate the veracity of my claim, in this series of articles Iím going to introduce you to using the Object Value pattern. This is a fundamental paradigm in DDD (and in OOP by the way) which permits you to create value objects with minor headaches.

But wait a minute! You may be wondering what a value object is, right? Well, simply put, a value object is a raw object whose equality with reference to other objects is based on the values (hence its name) assigned to its fields, and not on its identity.

If this explanation sounds confusing to you, let me elaborate on the concept with an example: if two user objects have the same name (which can occur in the real world) and thereís no identity field that allows you to differentiate one from the other, theyíre value objects because their equality is based on the values assigned to their properties.

On the other hand, if each user has its own identity (usually in the form of an ID), they suddenly become entities. The same rule can be applied to other simple objects as well, like dates, email addresses, URLs and so forth. Got the point? I hope so.

Also, in many cases a value object exposes a characteristic known as immutability, which is nothing but a fancy way to say that once its fields have been populated with the mandatory values, they canít be changed later. This makes lot of sense for preventing inconsistencies between domain objects that make reference to the same value object. For the moment, though, Iím not going to complicate the theory of value objects with additional explanations, as each concept will be properly clarified by means of a concrete example.

So far, so good. Having roughly outlined what the Value Object pattern does, itís time to start showing you some functional code samples, which hopefully will help you understand the actual functionality of value objects in PHP. Letís get started!

Implementing the Value Object pattern: building a basic URL class

Since my purpose here is to demonstrate how to create value objects that may exist in a real-world environment, the first step that Iím going to take will consist of defining a simple class. It will be responsible for modeling basic URLs. In line with the concepts deployed in the introduction, every instance spawned from the class will be immutable, meaning that once its fields have been populated, they simply canít be altered any further.

In reality, several approaches can be used for building immutable value objects. For instance, Matthew Weier OíPhinney shows how to accomplish this by using a combination of a private property and the magic ď__set()Ē method, while Ralph Schindler relies on exceptions to build immutable objects derived from the ArrayObject PHP built-in class. While all these examples are perfectly valid and functional, in this case Iím going to take an approach similar to Giorgio Sironiís, which in my opinion is the easiest to follow. Needless to say, youíre free to pick the method that best fits your needs.

Having clarified that point, hereís the initial definition of my own immutable URL-modeling class:

(Url.php)

final class Url
{
    private $_scheme; 
    private $_host;
    private $_path;
    private $_queryString;
   
    // constructor
    public function __construct($url)
    {
        if (!filter_var($url, FILTER_VALIDATE_URL, array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_FLAG_HOST_REQUIRED))) {
            throw new UrlException('The specified URL is invalid.');
        }
       
        $url = parse_url($url);
        $this->_scheme = $url['scheme'];
        $this->_host = $url['host'];
       
        if (isset($url['path'])) {
            $this->_path = $url['path'];
        }
       
        if (isset($url['query'])) {
            $this->_queryString = $url['query'];
        }
    }
}

 

(UrlException.php)

<?php

class UrlException extends Exception{}

Even though in its current state, the above ďUrlĒ class does nothing especially interesting, it indeed follows the model of an immutable value object. First, via its constructor, it accepts a string containing the URL that will be modeled, which is validated at a basic level by using a few PHP filters. And then, the scheme, host, path and query string parts of the given URL are assigned to the classí fields.

By far, the most interesting facet of this process is that the values assigned to the pertinent fields are no longer modifiable, since the class doesnít declare any mutator method for them. This means that instances created from the class will be immutable by default. On the other hand, two or more instances will be equal only if the values assigned to their properties are the same. In a few simple steps, I managed to create an immutable value object that models basic URLs. That was much easier to accomplish than you thought, wasnít it?

Itís valid to point out that while the fields of the previous ďUrlĒ class are immutable, they should be accessed from client code through the corresponding getters. Since this is a must for good object-oriented programming, in the next section Iím going to add those additional methods to the class. This will extend its core functionality a bit.

To see how these methods will be properly implemented, click on the link that appears below and keep reading.



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