mehlah/li3_jbuilder

通过 DSL 创建 JSON 结构

安装: 8

依赖项: 0

建议者: 0

安全性: 0

星标: 1

关注者: 5

分支: 0

公开问题: 0

类型:lithium-library

dev-master 2013-04-12 09:28 UTC

This package is not auto-updated.

Last update: 2024-09-14 13:50:51 UTC


README

将 JSON 响应添加到应用程序中 Build Status

为了展示这个库的用途,我们将使用一个简单的应用程序。这个应用程序有很多 discussions,我们希望为每个 discussion 添加一个 JSON 表示形式,我们可以通过在讨论的 URL 后附加 .json 来获取。如果我们这样做,我们将看到讨论的 JSON 表示形式。

自定义响应

返回的 JSON 包含了讨论的所有属性,但如果我们想自定义它怎么办?事情开始变得复杂。我们可以在讨论上调用 to('json') 并自定义返回的内容。假设我们想要从讨论中获取 id、主题和内容字段,以及其作者和讨论消息的相同字段。

public function show() {
	$discussion = Discussions::find($this->request->id);

	if (!$discussion) {
		return $this->redirect('/discussions');
	}

	if ($this->request->is('json')) {
		// we don't want to expose this
		unset($discussion->created_at);

		// additional data comes from associated Author and Comments records.
		$discussion->author = [
			'name' => 'Mehdi Lahmam B.',
			'id' => '1234'
			];
		$discussion->comments = [
			['content' => 'w00t', 'author' => 'John Doe'],
			['content' => 'This is sexy', 'author' => 'Jimmy']
		];

		return compact('discussion');
	}

	return compact('discussion');
}

我们可以通过再次刷新页面来尝试这样做。当我们这样做时,我们将看到包括关联的作者和评论记录的定制 JSON 响应。

这可以工作,但我们使用的代码并不美观。

更好的方法

即将推出!

致谢

基于 原始,以及一个 PHP 端口