Reputation: 179
The way I have PHP set up is that everything goes to a central file called Router. the router gets a parameter action and calls that method.
In Node.js, you can have get and post versions of the same method. I was wondering, is something like this possbile in PHP?
Basically I would like this to happen:
Have an add method.
Page 1 has the add button. The add button goes to the form that needs to be filled out to add an item - a get request. Upon clicking, the add method is called.
Page 2 has another add button. The add button now inserts using form data and adds an item - a post request.
Now, both call the same method, but in the file a get version of the method is defined and post version of the method is defined.
Was wondering if this is possible without having two methods with different names.
Upvotes: 0
Views: 98
Reputation: 19325
You can use $_SERVER['REQUEST_METHOD']
to determine whether it is GET or POST. A primitive attempt might look like this:
function handle_request() {
$action = $_REQUEST['action'];
$verb = tolower($_SERVER['REQUEST_METHOD']);
// create string representation of the function to call, eg. post_add, get_add
call_user_func( $verb.'_.'$action, $_REQUEST);
}
}
If you do not wish to name the function differently:
function add() {
if (tolower($_SERVER['REQUEST_METHOD') == 'post') {
// run the post version
} else {
// run the get version
}
}
A full example implementing a REST API can be found here:
Upvotes: 1
Reputation: 9527
Try to use $_REQUEST
. It is universal replacement for $_POST
or $_GET
.
Upvotes: 0