URL: U R a Lifesaver!
There’s only one thing that sucks more than a Dyson Ball, and that’s dealing with complex URLs that have parameter strings so long it feels like the URL equivalent of a run-on-sentence that doesn’t seem to ever stop yet every piece has its own reason for being there. Do you feel my pain? Then read on to find eternal salvation….
What’s a developer to do when there’s no intuitive built-in method for dealing with these things? Enter the URL (a.k.a. MakeYourLifeEasier) class. Before we get into the nitty gritty, why don’t we let it show off a bit with a few examples.
/** * Example 1: Inspect a sample URL. */ $url = new URL('http://leeroy:jenkins@www.nickawilliams.com:1337/path/to/subdir/example.php?id=3&page=2#some_fragment'); echo 'Protocol: ' . $url->protocol; // Produces "Protocol: http" echo 'Host: ' . $url->host; // Produces "Host: www.sitecrafting.com" echo 'Port: ' . $url->port; // Produces "Port: 1337" echo 'Username: ' . $url->username; // Produces "Username: leeroy" echo 'Password: ' . $url->password; // Produces "Password: jenkins" echo 'Path: ' . $url->path; // Produces "Path: /path/to/subdir/example.php" echo 'Fragment: ' . $url->fragment; // Produces "Fragment: some_fragment" foreach($url as $key => $value) { // Produces: echo $key . ' = ' . $value; // id = 3 } // page = 2 /** * Example 2: Adding to the current page's URL. */ // An empty URL defaults to the currently executing script's URL. // Let's assume the same URL from the previous example. $url = new URL(); // Modify the page number. $url['page'] = 3; // Link to the next page. echo '<a href="' . $url . '">Next Page</a>'; /** * Example 3: Copying an existing URL. */ $url = new URL(); // Calling URL::copy() makes a clone of the URL object and all its properties. // Pass in an array of key/value pairs to simultaneously assign new values. // Link to the previous page. echo '<a href="' . $url->copy(array('page' => 1)) . '">Previous Page</a>'; // Link to the next page. echo '<a href="' . $url->copy(array('page' => 3)) . '">Next Page</a>';
As you can see, this class is great for both inspecting and modifying URLs. The class itself takes advantage of some of PHP’s advanced SPL features:
- The various components of a URL are accessed as properties of the URL class:
$url->protocol
- Query string variables are accessed simply by treating the URL object as an array:
$url['page']
- You can even loop through it or call count() on it like a real array.
- Simply use (or cast) the object as a string to get the assembled URL:
echo ‘URL: ‘ . $url
And now for the moment you’ve all been waiting for, the guts.
Hopefully this will find its way into your life, saving you some hours and possibly a few bottles of aspirin. If you’ve found this class useful or have any suggestions for improvements, feel free to share in the comments!
Download: URL.php (zip)