【问题标题】:Is it possible to detect if a HTTPRequest is available?是否可以检测 HTTPRequest 是否可用?
【发布时间】:2019-07-26 08:21:10
【问题描述】:

银条版本:4.2

我有一个自定义的AssetAdapter,它可以根据当前请求对文件系统进行一些更改。我正在使用注入器来获取请求:

$request = Injector::inst()->get(HTTPRequest::class);

在大多数情况下,这工作正常,但在几个孤立的情况下,我得到了错误:

ERROR [Emergency]: Uncaught ArgumentCountError: Too few arguments to function SilverStripe\Control\HTTPRequest::__construct(), 0 passed and at least 2 expected
IN GET /ecms-client/public/markseen
Line 157 in /project/path/vendor/silverstripe/framework/src/Control/HTTPRequest.php

这似乎是 GraphQL 和资产的问题/冲突(GraphQL 似乎并不总是有当前请求可用)。我想知道在尝试通过Injector 获取它之前是否有办法检查当前的 HTTPRequest 是否可用/设置?

【问题讨论】:

    标签: php silverstripe silverstripe-4


    【解决方案1】:

    是的,Injector::inst()->get() 将创建一个新实例(如果尚不存在)。由于HTTPRequest 在构造过程中需要两个参数,所以会出错。

    您可以使用->has()检查是否存在:

    if (Injector::inst()->has(HTTPRequest::class)) {
        $request = Injector::inst()->get(HTTPRequest::class);
        // do something
    }
    

    【讨论】:

    • 天啊,这让我头疼!该解决方案完美运行!
    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2021-12-25
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多