我正在尝试使用 Symfony2 和 FOSRestBundle 来构建 REST 框架,但失败得很惨。
我已完成以下操作:
在我的 deps 文件中:
[FOSRest]
git=git://github.com/FriendsOfSymfony/FOSRest.git
target=fos/FOS/Rest
[FOSRestBundle]
git=git://github.com/FriendsOfSymfony/FOSRestBundle.git
target=bundles/FOS/RestBundle
[JMSSerializerBundle]
git=git://github.com/schmittjoh/JMSSerializerBundle.git
target=bundles/JMS/SerializerBundle
在我的 apps/config.yml 中
fos_rest:
view:
formats:
rss: true
xml: false
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
sensio_framework_extra:
view:
annotations: false
在我的 Controller 中:
namespace Rest\WebServiceBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
class DefaultController extends Controller
{
public function indexAction($name)
{
$view = View::create()
->setStatusCode(200)
->setData($name);
return $this->get('fos_rest.view_handler')->handle($view);
}
}
当我访问 URL:http://local.symfony.com/web/app_dev.php/hello/test 时
我得到:
Unable to find template "".
500 Internal Server Error - InvalidArgumentException
2 linked Exceptions: Twig_Error_Loader » Twig_Error_Loader
该文档对我来说似乎很困惑,我无法继续。我想要的只是能够将数据数组传递到 Controller 并返回 JSON 格式。有人可以帮忙吗?
最佳答案
在 config.yml
的 formats
部分中,您必须启用 json 格式并禁用其他格式,并将默认 _format
值设置为路由中的 json 。例如
# app/config/config.yml
fos_rest:
view:
formats:
json: true
rss: false # removing them will also work
xml: false
#.......
#bundle/routing.yml
route_name:
pattern: /route
defaults: { _controller: Bundle:Controller:Method, _format:json }
或者,在 Controller 中你可以这样做
$view->setFormat('json');
另请查看文档中给出的示例链接。
关于php - 无法使用 FOSRestBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573764/