Best way for JSON output

2,166 views
Skip to first unread message

Mitch Pirtle

unread,
Jul 2, 2009, 5:48:23 PM7/2/09
to 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

unread,
Jul 2, 2009, 6:47:51 PM7/2/09
to 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

unread,
Jul 4, 2009, 3:28:15 PM7/4/09
to 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

unread,
Jul 29, 2009, 2:04:51 PM7/29/09
to 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
Reply all
Reply to author
Forward
0 new messages