0

I already have a mobile app that retrieve some data from database, show it to the user by php scripts that execute querys on a database, and return a json with results to my app.

I also have a desktop app that use other php scripts to retrieve data on same database, and next step is to implement a website too.

Now I think that having a script for each operation that my app support is not the best practice, so I've decided to use Symfony framework for organize my server scripts better.

For now I've created a new PHP Symfony project, replicated my database on localhost, generated a bundle for db operations, mapped sql tables, generated entities and generated a crud controller for each entity.

Now I don't know how to go ahead.

How can I make my project return only json messages for each operation (and not an html page with result as happen by default)?

1 Answer 1

2

You must return the json string at the end of an action!

e.g.

public function ajaxAction(Request $request){

    //get some data from doctrine, do other stuff

    //generate a json string from it and return it

    $json = json_encode($data);
    $response = new Response($json, 200);
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

Now your Route for that action only return the json string!

Sign up to request clarification or add additional context in comments.

2 Comments

So when i deploy the website (probably i'll buy a template), i just need to call link for get data, then parse json? It's a good practice for this kind of scenario?
@giozh yes, you'll only need to call the links. The site that called the link only need to parse the json then and work with the data that comes from the link. That's nothing more then a normal API implementation. This is the best practice scenario since json is lightweight and easy to parse by almost every programmig language. Only xml can be read by more languages, but xml has way more overhead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.