PHP rest wrapper for api endpoint with query - php

I have an api that I can test at it's current endpoint with a query (this is for a search with autocomplete) like so:
.../search/autocomplete?query=product123
And this returns the results expected. However, this is the first time I've made a php rest/wrapper for an api using a query instead of fields.
My question is, using a hard coded test variable below, How should I properly pass this into the function and properly query the endpoint?
This is a test but basically it's going to be used as someone types into a search box and passes from there, so same idea.
Am I on the right track with this?
$testVariable = "product123"
public function getSearch($testVariable)
{
return $this->get("/search/autocomplete?query={$testVariable}");
}

Related

How to get arguments from route PHP

So I have a doubt, and I'am not really sure how to solve it.
I'am trying to make a rest API with PHP, no framework, nothing, so first of all I thought of making
The functions: get, show,create, update, delete.
Like that I will be able to call the function
needed, the first parameter will be the url where is going to make the petition and the second one will be a function, like this, for example:
function get($url,$func){
}
I did my research and I know from where to start initially,
However, my problem starts when I want to get the parameter of the route,
Like for example if I use a framework, I will be like this:
SHOW
$app->post("/show/{id}","show_f");
in the above example the route will be "show" and the "id" will be the argument.
However, my problem is how can I get the argument (id) of the route
Do I need to convert to an array the $url value? (like this: explode('/', $url);),
so like that when I receive the initial value will be a string, however, when I split it, I will get an array of the route and the argument.
Does it sound reasonable, or do I complicate myself?

How to call a function using GET Request in Yii2

I am trying to get a hang of Yii2 and learing it. I have now a quick question.
I have a function written in my ProductController.php called actionGetPhoneForCustomer with the parameter $product. The action calls another action within itself, that has an ActiveQuery in it. The query works great, the tests run where successful.
Now I want to have a simple GET request to call said function. However, it does not work properly. Am I writing the request wrong somehow? Below is the request I am trying to use and I always get a 404Error. There really is no page needed, it's just a simple echo that should be returned. Below is the request as I am writing it.
http://localhost:8080/myproductapp/web/index.phpr=product%2FgetPhoneForCustomer&product=Keyboard
And this is the action:
public function actionGetPhoneForCustomer($product) {
echo $this->getProductBySaleSatus($product);
}
What am I doing wrong here? Am I missing something in the URL? Any help would be greatly appreciated.

wordpress, why return $this->get_posts(); returns values?

I was trying to find out how wordpress process each request and returns the result. I found wp() function calls $wp->main() which in turn calls $this->query_posts(); and which calls $wp_the_query->query($this->query_vars) function in query.php file. The query() function calls return $this->get_posts(); and return the result.
My question is didn't see any any variables receiving this returned value so why this function has return, even though the wordpress works if I remove the return from the code. so what is the purpose of this return, (I guess this code saves the contents (posts) to $this->posts variable). btw I am using wp 3.6
I believe this answer may provide what you're looking for:
https://wordpress.stackexchange.com/a/1755
Specifically this image (which I did not create myself):
The use of return is related to php (also used in other languages) not only WordPress. When execution reaches a return statement, the function stops and returns that value without processing any more of the function. A return with no value returns null and If there is no return keyword at the end of a function then, in this case too, a null value get returned.
Using a return statement at the end of a method/function is a good coding practice, it just returns the execution control back to the point, from where it started and it also Prevents Code Injection in PHP include files. Also, check this.
Short Answer:
There are other functions that make use of the returned value, mostly in themes and plugins, but also in WP core. examples are given below.
Long Answer:
In wordpress the WP_Query::query() method is used for getting posts from the DB.
This is done by providing certain criteria for selection, ie: the query_vars.
Based on which the posts are retrieved and made available.
now, in the case mentioned by you what is of important is the call stack, ie the path used to call the function.
ie:
wp() --->
[WP->main()]-->
WP->query_posts() {here the query is
called on the global
wp_query Object}
-->WP_Query->query()
In WP->main(), the parse_request methond is called, which creates the query_vars from the REQUEST_URI.
so whatever post is fectched depends on the requested pages URL. i.e the criteria for selection is provided by the requested page's url.
And since the query method is called on the global wp_query object, there is no need to return it.
This forms the main path, ie: global wp query, and request uri query vars.
But in cases, like in themes, plugin, when you need to fetch additional posts. you will create a new wp query object, and use the query method.
eg: to fetch all posts by 'john'. in these situation the value returned by the query method is used.
$wpquery = new Wp_query();
posts = $wpquery->query("author_name=john");
Some functions that uses it:
wp_nav_menu_item_post_type_meta_box /wp-admin/includes/nav-menu.php
wp_link_query /wp-includes/class-wp-editor.php

Doing an Ajax GET request to return data to PHP

I want to make an Ajax search request agains an API and get the data returned to my PHP file, right now I'm using Javascript and jQuery to do the job. But I want to let PHP do all the job, simply because I don't want my API key to be public and I may want to cash the data in a database further on. It seems that it should be simple, but I just can't figure out how to do it clean, call javascript and return or how to "integrate" it with PHP.
I am doing my PHP in the MVC pattern, like so:
Controller called from "mastercontroller/index":
class SearchController {
public function DoControl($view, $model) {
$ret = "";
$ret .= $view->GetSearchForm();
if($view->TriedToSearch()) {
if($view->GetSearchString()) {
$ret .= $model->CheckSearchString($view->GetSearchString());
} else {
// Didn't search for anything
}
} else {
// Didn't press the search button
}
return $ret;
}
}
My view is returning an HTML form, checking if submit is pressed and also returning the searchstring, that I am sending in to my Model above.
Model:
class SearchModel {
public function CheckSearchString($searchString) {
// 1. Call Googlebooks api with the searchstring
// 2. Get JSON response to return to the controller
// 3. The controller sends the data to the View for rendering
}
}
I just can't figure out how I should do it.
I'm not entirely sure, but you seem to be asking how to perform an AJAX request without JavaScript. You can't do that -- it's not possible to use the XmlHttpRequest object without JavaScript. That's, according to legend, the origin of the "J" in the AJAX name.
It sounds like you need to use REST to call specific API's. RESTful state allows you to use web services to return specific data according to a predefined API. Data can be returned in XML or JSON.
You can do this very easily with PHP's cURL implementation using whatever keys Google gives you.
See Google's Google Books API Family page for links to PHP API and sample code.
Would the below practice be useful to you? If you just want to implement ajax functionality in your code.
Simple AJAX - PHP and Javascript
I am sorry for mistaking the content. How about the two below:
simple http request example in php
PHP HTTP-Request * from another stackoverflow question
But I think ajax is main in client program meaning. At the server-side, just call it http request.

get object data in mvc structure

I'm working with a PHP MVC Framework. Works really well. I like the separation of the business layer (model) with the business logic (controller). But i just stumbled upon a problem. Here's the thing:
Suppose i navigate to the following url:
http://localhost/user/showall/
In this case the userController.php is called and within that file there is a method showallAction() which gets executed.
In the showallAction() method i simply do a request to a model which gets all the users for me. Something like this:
public function showallAction()
{
// create userModel object
$users = new userModel();
// get all users and assign the data to a variable which can be accessed in the view
$this->view->users = $users->getAllUsers();
// render views
$this->view->render();
}
So this method gets all the users, assigns the data returned from the userModel to a variable and i can easily work with the returned data in my view. Just a typical MVC thing.
Now here comes the problem.
I also need to create a native iphone variant. Ofcourse the looks will be totally different. So all i actually want to do is to request this url:
http://localhost/user/showall/
And that it just gives me the array (in json format) back. So i can use that for the mobile development.
But this obviously can't be done right now because the showallAction() method assumes that it is for web browser display. It doesn't echo JSON formatted, instead it simply assings the array of users to a variable.
So that means i have to create another method "showallMobileAction()" in order to get the data, but specifically for the mobile device. But this is not an elegant solution. I'm sure that are better ways...
Anyone any idea how can i solve this problem??
In your situation i would modify the routing mechanism.
It would be useful, if you could add extension at the end of URL, which represents the format you expect, like :
http://foo.bar/news/latest >> HTML document
http://foo.bar/news/latest.html >> HTML document
http://foo.bar/news/latest.rss >> you RSS feed
http://foo.bar/news/latest.json >> data in JSON format
It's a simple pattern to recognize. And you can later expand this to add .. dunno .. pdf output, or Atom feeds.
Additionally , two comments :
Model is not a type of objects. Instead it is a layer, containing objects responsible for business logic, and objects responsible for data storage/retrieval.
View should be a full blown object, to which you bind the domain objects (objects responsible for business logic).
You could pass parameters to your url:
/user/showall/json
and get the third URL segment with a custom function or a built-in one. For instance, with CodeIgniter: $this->uri->segment(3).
Some frameworks will pass the additional parameters to your method. Just try this with the URL I wrote above:
public function showallAction()
{
print_r(func_get_args());
}
I'm not familiar with PHP MVC but in general terms I'd use the "accepts" HTML header field to request the response in either "text/html" or "text/json", the controller would check for the accepts type and return the response accordingly.

Categories