Home arrow PHP arrow Page 2 - PHP: Modeling a URL Class

Adding getters to the Url class - PHP

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

If you've dealt with classes frequently, you’ll know that coding getters that provide access from client code to their protected or private fields is a breeze. The previous “Url” class is no exception. Since the class is already immutable (or the objects derived from it, to be more precise), it’s desirable to make it a little more functional by adding some accessors to it. So, here they are:  

// get the scheme part of the URL
public function getScheme()
{
    return $this->_scheme;
}

// get the host part of the URL
public function getHost()
{
    return $this->_host;
}

// get the path part of the URL
public function getPath()
{
    return $this->_path;
}

// get the query string of the URL
public function getQueryString()
{
    return $this->_queryString;
}

That’s not rocket science. Now that the proper getters have been implemented, each private property that the class declares can be accessed by client code in a truly simple manner. This is actually OOP 101, but for the sake of completeness I included the definition of these methods, so you can see how they look and even introduce your own tweaks into them.

And now that the methods have been adequately defined, we're going to add them to the definition of the “Url” class. This will be done in the course of the following section, so keep reading. 

The finished version of the “Url” class

As I noted above, here’s the finished version (at least for the moment) of the sample “Url” class, after adding to it the set of getters implemented previously. Check it out:

(Url.php)

<?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'];
        }
    }
   
    // get the scheme part of the URL
    public function getScheme()
    {
        return $this->_scheme;
    }
   
    // get the host part of the URL
    public function getHost()
    {
        return $this->_host;
    }
   
    // get the path part of the URL
    public function getPath()
    {
        return $this->_path;
    }
   
    // get the query string of the URL
    public function getQueryString()
    {
        return $this->_queryString;
    }
}     

Mission accomplished, at least for the moment. At this stage, I've built a basic class which is capable of modeling immutable value objects. While this is good, I'd like you to look more closely at this class. Admittedly, it’s nothing but an immutable structure that acts like a container for the different parts of a well-formed URL. What if I want to implement some kind of behavior, like appending additional parameters to its existing query string?

In a case like this, the “$_queryString” property should be altered in some way, thus breaking up its immutability! Well, fear not, because here’s exactly where another feature of the Object Value pattern comes into play. If you try to mutate an immutable object, the process should always return a new object of the same type.

Now, if I translate this concept to my “Url” class, any method that attempts to alter its query string field will result in the creation of a new “Url” object. Got the idea? Don’t worry if you don’t yet, as in the next installment I’m going to add such a method to the class. This way, you’ll be able to see its concrete implementation and catch its driving logic. 

Final thoughts

In this introductory part of the series, I provided you with an overview of what the Object Value pattern is and how to implement it in PHP. In the example above, you learned how to define a basic URL class that can be used for creating easily immutable value objects.

As I said before, though, the class has no behavior beyond acting like a simple data container. However, this is about to change, since in the next tutorial I’m going to add to it a method that will append extra arguments to its query string. In keeping with the schema imposed the Value Object pattern, the method will return a new “Url” object, therefore keeping the class’ immutability intact.

Don’t miss the next part!



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