Best way for JSON output

Visto 2.162 veces
Saltar al primer mensaje no leído

Mitch Pirtle

no leída,
2 jul 2009, 17:48:232/7/09
a joomla-...@googlegroups.com
Here's one that might have a simple solution that is staring me in the face:

Imagine a component that has a model with several methods - getItem,
getItemByName, getItemExpiration, getItemShoeSize, getPizzaRecipe and
whatnot...

I want the view to return JSON strings for each, and using $task to
determine which to execute. So far, so good.

However I find myself using one view, and in the view class grabbing
the task and executing the task in the model call. Something about
this just doesn't seem right, as the V shouldn't be calling variable
methods, right?

On the flipside, I'm not really interested in creating separate views
for every task either.

Is there a better approach?

-- Mitch

Louis Landry

no leída,
2 jul 2009, 18:47:512/7/09
a joomla-...@googlegroups.com
I would just go with simplicity.


class MyController extends JController
{
    function someTask()
    {
        // Get the application object.
        $app = JFactory::getApplication();

        // Get the model.
        $model = $this->getModel('MyModel');

        // Get the data from the model.
        $data = $model->getData();

        // Check for errors.
        if ($model->getError()) {
            // Do something.
        }

        // Echo the data as JSON.
        echo json_encode($data);

        // Close the application.
        $app->close();
    }
}

No need to bother with views if you don't want to.  As an aside to that, you may want to set some response headers with JResponse for mime types or whatnot... up to you.  That is perhaps an overly simplistic controller task but you can see the gist of it.

- Louis

--
Development Coordinator
Joomla! ... because open source matters.
http://www.joomla.org

Mitch Pirtle

no leída,
4 jul 2009, 15:28:154/7/09
a joomla-...@googlegroups.com
Yeah, when JSON enters the picture, we end up with MC and no V ;-)

Thanks for the reality check, Louis.

-- Mitch

blechler

no leída,
29 jul 2009, 14:04:5129/7/09
a Joomla! CMS Development
Bravo Louis!

This is exactly what I have been seeking for a long time. Concise, to
the point, easy to understand. If only you were writing the Joomla
docs, things would be much better.

Bernie
Responder a todos
Responder al autor
Reenviar
0 mensajes nuevos