By dharmatech on
This is probably a newbie question but I couldn't find the answer in the coding standards.
When a hook_menu implementation in a contributed module needs to reference the URL arguments is it considered better to code the reference as "$_GET['q'] == " or as "arg(0) =="? All I could find in the coding standards was a statement that referencing arguments to the hook function is more readable than calls to arg() but hook_menu doesn't have such arguments
TIA -- Walt
Comments
$_GET['q'] is the entire URL
$_GET['q'] is the entire URL string after the base_path. arg() returns a specific part between the slashes. In general, this makes arg() easier to use.
That statement in the coding standards is meant for other hooks and functions because it is assumed that hook_menu will call them and pass the needed URL arguments to the function directly. hook_menu() has the context for the path, so it's easier to figure out what arg() will return. Somewhere else in the file, someone reading it will think "What is arg(4) supposed to be here?"
-----
Übercart -- One cart to rule them all.
Depends on what you are
Depends on what you are trying to do, b/c they have different functions.
If a user browses to www.example.com/node/1 , then $_GET['q'] contains "node/1". arg(0) returns "node", and arg(1) returns "1". In other words, $_GET['q'] returns the entire query string., arg() returns specific parts of the query string.
For my implementations, I have almost exclusively used arg(). It is better suited for my needs.
- Corey
It seems that either
It seems that either approach could be used. I don't think $_GET[] is Apache-specific the way, for example, $_SERVER[] is. My question was whether there is a coding standard on the subject or is it just developer's personal preference.
---
DharmaTech
68 S. Main St., Suite 400
Salt Lake City, UT. 84101
http://www.dharmatech.org
The advantage of $_GET['q']
The advantage of $_GET['q'] over $_SERVER[] is that $_GET['q'] is set by Drupal. This is most evident when you are using path aliases. If, for example, you browse to www.example/com/my_vacation , where "my_vacation" is an alias for "node/123", then Drupal de-aliases and changes $_GET['q'] to "node/123" during the page initialization. $_SERVER[] would show you the "my_vacation" version.
Now, as to why you might use $_GET['q']: Use this when you want to match only a specific url, such as "node". This will not match "node/123", "node/add", etc.
Use arg() when you want to match parts of the query string, or want to know the value of a specific part of the query string.
Neither method is wrong, and I'm sure both are used on occasion, with arg() being more prevalent. Use whichever method is needed (and quicker) for your situation.
- Corey