How to use a php restful api-centric design intern

2019-04-09 07:11发布

问题:

I want to create a php restful api-centric web application/website where I have the data/api that gets called from my front end code. Besides making HTTP/curl request calls each time I load a page, what can I do for internal API calls using frameworks like slim?

I'm not sure of a way to include the api for internal use in my front end code and still keep it apart.

My thoughts was something like this:

"example.com/api/story/todays-weather/"
pulls in the json formatted story with a http request with curl or Ajax

But instead could I do something like:

require("/api/internal.php");
$uri = "/story/todays-weather/";
$call = api::getStory($uri);
$result = json_decode($call);
.....

Am I headed in the right direction or am I way off?

The api and front code are on the same cloud box (Amazon E2/LAMP) and I am planing on using memcached for the api.

回答1:

So you wan to have a code separation between your API and front-end stuff ? You could use Slim Framework to do that so you will have an easy maintainable code. Slim Framework is very easy to write models and also prepare the data for future use and even cache it.

Also have a look at this list of PHP RESTful API Frameworks: http://davss.com/tech/php-rest-api-frameworks/

You could also take a different approach and use front-end models to do both the code separation and have a nice code structure. For that I recommend Backbone.js which will provide some nice key-value bindings and event handling for your front-end code.



回答2:

Use the MVC pattern in our favor, write one model with 2 different views. Look like you are doing something similar here:

require("/api/internal.php");
$uri = "/story/todays-weather/";
$call = api::getStory($uri);
$result = json_decode($call);

That way you have a separation between the Frontend and the API, but the important part is the same, reducing the code duplication.

Look the right direction to me.



回答3:

I have a PHP webservice that feeds another php page, basically the user can hit a button online and the webservice is called has many times as necessary making it easy to maintain, not sure if this is what you need but it works fine for me right now, here is part of the code.

My webservice returns json or xml, I found this piece on the web and modified to fit my needs.

<?php 
case 'whateveryourwebserviceaction': 

       $params = array("test");
        $tsql = "select * from test where test=?";
        /*Execute the query with a scrollable cursor so
          we can determine the number of rows returned.*/
        $cursorType = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
        $getProducts = sqlsrv_query($conn, $tsql, $params, $cursorType);
        if ( $getProducts === false)
        die( FormatErrors( sqlsrv_errors() ) );

        $posts = array();
        while( $post = sqlsrv_fetch_array( $getProducts, SQLSRV_FETCH_ASSOC))
        {
            $posts[]=array('post'=>$post);

        }


   break;


  }

    if($format == 'json') {
        header('Content-type: application/json');
        echo json_encode(array('posts'=>$posts));
    }
    else {
        header('Content-type: text/xml');
        echo '<posts>';
        foreach($posts as $index => $post) {
            if(is_array($post)) {
                foreach($post as $key => $value) {
                    echo '<',$key,'>';
                    if(is_array($value)) {
                        foreach($value as $tag => $val) {
                            echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
                        }
                    }
                    echo '</',$key,'>';
                }
            }
        }
        echo '</posts>';
    }
?>

And here is how i call this thing from my php page using jquery.

$.ajax({
                        type: "GET",
                        url: "htto:\\server.com?action=whateveryourwebserviceaction&format=json",
                        dataType: "xml",
                        success: parseXml,
                        error: function (xml) {
                            alert(xml.status + ' ' + xml.statusText);
                            }});

you can call this function on any user input and refresh with the results provided by the webservice, hopefully this will help you keep going.