【问题标题】:Override JSON view in RequestHandler in CakePHP在 CakePHP 的 RequestHandler 中覆盖 JSON 视图
【发布时间】:2017-07-04 05:39:48
【问题描述】:

我想在 RequestHandler 中重写 JSON View。所以有一个文件project_root/lib/JsonView.php。我想做的是

  • JsonView.php 文件导入到project_root/app/View/CustomJsonView.php 中的另一个文件中。 (我想我可以使用App:import,对吗?)
  • 在 requestHandler 中选择这个文件作为自定义,如下所示:

public $components = array('RequestHandler' => array( 'viewClassMap' => array('json' => '/right/way/to/this/file/CustomJsonView', )));

但是我该如何为这个文件写正确的方式呢? 我也看到了这个https://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent::viewClassMap 但是没有关于文件的正确路径的解释。我的 CakePHP 版本是 2.4.4。

【问题讨论】:

    标签: php json cakephp requesthandler


    【解决方案1】:

    您不应该传递完整路径,而是“短类名”,就像链接示例中所示,其中ApiKit.MyJson 指的是ApiKit 插件中的MyJsonView 视图类,它可以位于app/Plugin/ApiKit/View/MyJsonView.php.

    如果您遵循约定并将CustomJsonView 类放在app/View/CustomJsonView.php as shown in the docs 中,那么您只需在请求处理程序viewClassMap 选项中将CustomJson 作为短类名传递。

    您是使用App::import() 还是仅使用require 来包含/lib/JsonView.php 文件,取决于您,两者都有效。无论如何,您必须确保您导入的任何内容都不会与现有的类名冲突(JsonView 是一个保留名称,因为它已经存在于核心中),并且它遵循 CakePHP 视图类命名约定,或者你必须扩展它。

    另见

    【讨论】:

    • 谢谢,它有帮助。我只是以这种方式 App::uses('JsonView', 'View'); 包含文件,然后扩展它。在 RequestHandler 中,我可以仅按名称调用它,自定义文件位于 app/View/ 文件夹中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多