Joomla! Dev – The Wonders of JURI
So when you work on Joomla! components and modules (or at least when I do), you run into a need to manipulate the request URI/URL. This is particularly useful when you want to create permalinks without some creative server/application level URL rewriting. Joomla! provides a very nice class called JURI for doing this. JURI is actually just a wrapper around the PHP class parse_url but it is an incredibly useful one.
I’m not going to go through the whole class as the documentation is readily available here for you to read at your own leisure however I will go through a few usage examples where it has come in rather handy for me.
The first uses are rather innocuous:
$currentURI = JURI::getInstance(); $myURI = JURI::getInstance( $myURL );
These two lines each give me a JURI object. The first produces a JURI object based off the current request URL/URI. The second creates a JURI object from the URL sent in. In some cases, I want to modify the current URI (figure out where I am in the menu system, analyze query string variables passed in, etc) and in some cases I want to build my own new URL. JURI gives me the ability to do both easily.
So now that we have our URI/URLs, we can start playing with them and the area that we generally want to play with the most is the query string. JURI provides three methods that see the most use in this area:
$myVar = $currentURI->getVar('myVar'); $currentURI->setVar('myVar', 'myNewVarValue'); $currentURL->delVar('myVar');
The first line above gets the variable from the query string that looks like “myVar=…” The second line sets that same variable in the query string to a new one (”myVar=myNewVarValue”). The third line removes the variable from the query string if it exists. These three methods let me do pretty much whatever I want to the query string.
Of course, there are times when you want to rebuild the query string and not worry about what values are already present and JURI has a solution for that as well:
$myURIAndPath = JURI::getCurrent();
This will get you the current URI without the query string allowing you to repopulate it yourself.
None of these things are amazing or revolutionary but they’re useful, fairly intuitive, and a much cleaner alternative to calling parse_url directly. If you find yourself manipulating URLs/URIs in Joomla! then give them a try.