Return JSON with CodeIgniter
With the ever-increasing use of Javascript and AJAX related calls, it’s would be nice to be able to quickly build endpoints that returned JSON data for our web site. Whether your rolling your own code, using jQuery or using third-party tools like KendoUI, it’s very easy to return structured data in JSON format using CodeIgniter, a PHP framework from the fine folks at EllisLab.
随着与Javascript和AJAX相关的请求不断增长,最好能够快速构建能够为我们的网站返回JSON数据的端点。不论你是自己写代码、或者用jQuery、或者像 KendoUI一样的第三方工具,CodeIgniter都能很方便地返回JSON格式的结构化数据。CodeIgniter是一个由EllisLab的家伙们构造的PHP框架。
CodeIgniter uses a simplified Model-View-Controller pattern to help you build websites quickly without worrying about the plumbing code that seems to go into every web site you build. In a typical CI web site, each page request, calls a controller which is responsible for determining what data gets loaded and which view of the data will be presented to the requester. When loaded, the model is responsible for determining how the data is retrieved. This data is then returned to the controller which passes it on to a View. Views are responsible for taking the structured data and formatting it for presentation to the user (typically in HTML).
CI使用了一个简化的MVC模式来帮助你快速构建站点,从而使你不在受累于每个站点中都有的那些样板代码。在一个典型的CI站点中,每一个页面请求都调用一个控制器,由它来决定哪些数据被装载以及这些数据对应的哪个视图被呈现给用户。当模型被装载之后,它负责数据的获取。然后数据被返回给控制器,控制器把它们传递给视图。视图负责接收这些结构化的数据,并且将它们格式化以后呈现给用户(通常在HTML中)。
In this article, we’re going to look a quick and easy way to present that same data as JSON when we need it.
在这篇文章中,我们将要快速而简要地看一下当需要时怎么把这些数据用JSON格式呈现。
First, let’s take a look at our controller. We’ll use the index function which is called by default when no other function is defined in the page request URI. We’ll be passing our product ID into this function as part of the URI and CodeIgniter will use it as the $product_id parameter for this function.
首先来看一下我们的控制器。我们将使用index函数,当页面请求URI中没有其它函数时,index函数就会被调用。我们将把product ID作为URI的一部分传递给这个函数,CI将把它用作这个函数的参数$product_id。
//product.php
<?php
class Product extends CI_Controller
{
function index($product_id)
{
$this->load->model('Product_model', 'product');
$data['json'] = $this->product->get($product_id);
if (!$data['json']) show_404();
$this->load->view('json_view', $data);
}
}
?>
The controller will load our product model and then call the get method, passing in the $product_id parameter. The result of this method is stored into an element in an array called $data using the key ‘json’. We then check to make sure that we actually returned a product. If not, we’ll present a ’404 – Not Found’ error to the user’s browser. This is cleaner and safer than just sending back empty data.
这个控制器将会加载我们的product模型,并且调用get方法,传递进去$product_id 作为参数。这个方法的返回值被存储于 $data数组的一个元素中,以'josn'作为键。然后我们参查是不是的确返回了一个product。如果不是的话,就在用户的浏览器中呈现一个'404-Not Found'错误。这比我们直接发送一个空数据要更整洁和安全。
//product_model.php
<?php
class Product_model extends CI_Model
{
function get($product_id)
{
$result = $this->db->get_where('product', array('id' => $product_id));
return $result->row();
}
}
?>
Next the controller loads our very simple View passing in the entire $data array. Our view changes the output headers to application/json so the client making the request can handle it properly. In views, CodeIgniter will automatically create named variables for each of the keys in our array containing their corresponding values so our view now has access to a $json variable with our product data. We’ll simply call the PHP function json_encode() and return the results to the browser.
接下来控制器加载我们这个非常简单的View,并且将整个$data数组传递给它。View将输出的头部改成application/json,这样发送请求的客户端就能正确地处理它。在视图中,CI将自动为数组中的每个键创造一个同名的变量,并且把相关的值传递给这个变量,因此这个view能够访问一个$json变量,它的值就是我们的product数据。我们将会调用PHP的json_encode()方法,并且将结果返回给浏览器。
//json_view.php
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
?>
At this point, it will send back a nice JSON object. To make a call for this data, we can simply send a request to http://example.org/product/index/17, this tells CI to use the Product controller, call the index method and pass in 17 as the first parameter, in this case, $product_id. With some CI routing magic, we can shorten this to http://example.org/product/17 by adding the following line to our application\config\route.php file.
此时,上边的代码将会发送回一个JSON对象。为了获取个JSON对象,我们只用往http://example.org/product/index/17发送一个请求。这个请求告诉CI使用Product控制器,调用index方法,并且将17作为第一个参数传递给它,在本例中这个参数就是$product_id。参过CI的路由功能的一些小把戏,我们可以把这个请求缩短为http://example.org/product/17。为此,需要把下边的代码加进application\config\route.php文件。
$route['product/(:any)'] = 'product/index/$1';
The result of our efforts returns a nicely formed JSON object to use as we see fit.
我们努力的结果是返回了一个形式良好的JSON对象。
{
"id" :"17",
"name" :"Shoe - Black, Size 10",
"description" :"Skecher Sport, Brown w/Black, Size 10",
"issue_date" :"2012-03-31",
"show_as_new" :"No",
};