In drupal I want to define a URL without hook_menu(), so that I can link the URL to a function that will be return a JSON (I want to call it from JavaScript code).
function(){
$arr = array('a'=>'one', ..........);
return json_encode($arr);
}
Let me know how I can define a URL without hook_menu(), and link it to a function.
Yes, but No
If you absolutely must hack your way around something to call a specific php file. Like if you actually have a file at
/somepath/yourscript.phpthis could be callable from the general web. From there, you’d have to bootstrap Drupal yourself if you wanted anything in the Drupal namespace, or you’d have to userequireorincludefor each file where you wanted to call something… but it’s a bad idea.To bootstrap Drupal you’d need something like this:
At which point you are welcome to blow your own face off with whatever monstrosity you create. Hopefully, you’ve noticed that by bootstrapping Drupal you probably don’t save any time doing what you wanted in the first place by putting some rogue script in your file system.
The Drupal Way
Instead, use what Drupal gives you… A
menu hookimplemented as aMENU_CALLBACK. This will take a request right off the wire and send it to your function, as you desire. In your function, nothing stops you from looking at$_POSTand$_GETvariables, but you do get some Drupal sugar, in that yourMENU_CALLBACKcan accept URL parameters, check their validity, and pass them into your function so you have some assurances that you are working with valid data.You need only define your menu hook and your callback function. To use validation, you can use a named argument, like
%arginstead of the%in the example below. If you use the named parameters, you then would create a function calledarg_load($arg)which would make sure you have a valid parameter, then return a value to be passed into yourcallback_function. Here’s what your Drupal code might look like:I think the Drupal way is much better than the hacky one off file way for a few reasons. One, developers will understand what you are doing if you go the Drupal way. Two, you can change the URL as needed.
The only reason I’d go for the standalone file is if, the file has nothing to do with anything you need out of Drupal AND that action had to be damn fast. Like so fast the difference in time between bootstrapping Drupal and not would take too damn long. In that case I’d probably use apache or nginx to forward a URL path to the file somewhere else in the filesystem. And if this is the case, I’ll gladly eat my humble pie.