【问题标题】:Stripe Payments in PHP With Namespaces使用命名空间在 PHP 中进行条纹支付
【发布时间】:2013-07-30 18:21:48
【问题描述】:

我构建了一个使用命名空间和 PSR-0 自动加载的 PHP 应用程序。在尝试实现Stripe 库时,我发现它似乎无法加载这些类,因为它们没有命名空间。如果我手动包含文件,有没有办法不自动加载?

// Get Stripe Library
require_once(App\App::$APP_PATH . "/Extensions/Stripe.php");

// Set Key
Stripe::setApiKey($stripe['secret_key']);

在示例中设置密钥失败并出现致命错误,因为它认为当前文件的命名空间中存在Stripe 类。

我发现,如果我在命名空间声明下方添加 use Stripe; 行,它将起作用,但随后在 Stripe 库中的下一个类上失败。

我真的必须添加一个Use Stripe, Stripe_Customer, Stripe_xyz...; 行以让它正确加载文件(其中有超过 25 个文件)还是有更好的方法?

[编辑]

直到我听到是否有更好的方法,我已经这样做了:

// Import Non-Namespaced Stripe Library
use Stripe, Stripe_Account, Stripe_ApiConnectionError, Stripe_ApiError, Stripe_ApiRequestor, Stripe_ApiResource, Stripe_AuthenticationError;
use Stripe_Card, Stripe_CardError, Stripe_Charge, Stripe_Coupon, Stripe_Customer, Stripe_Error, Stripe_Event, Stripe_InvalidRequestError;
use Stripe_Invoice, Stripe_InvoiceItem, Stripe_List, Stripe_Object, Stripe_Plan, Stripe_Recipient, Stripe_SingletonApiResource;
use Stripe_Stripe, Stripe_Token, Stripe_Transfer, Stripe_Util;

【问题讨论】:

    标签: php namespaces stripe-payments


    【解决方案1】:

    您可以使用\ 指定您指定的类名是 FQNS,例如:

    <?php
    use \Stripe, \Stripe_Account;
    
    $stripe = new Stripe();
    $stripe_account = new Stripe_Account();
    

    或不带use 语句:

    <?php
    $stripe = new \Stripe();
    $stripe_account = new \Stripe_Account();
    

    【讨论】:

    • 这比我最终做的更好吗?您是在建议我基本上只使用命名空间前缀做同样的事情。这实际上需要做更多的工作。
    • 我只是建议解决您的问题:“我真的要添加Use Stripe, Stripe_Customer, Stripe_xyz...; 行吗”
    【解决方案2】:

    使用 composer 是最简单的方法(我保证!)

    只需install composer,然后是install stripe。一旦你安装了这些,只需浏览到你的项目文件夹并运行composer install。这将安装所需的依赖项,并将 composer 放在一个名为 vendor 的文件夹中。

    然后你简单地需要 autoload.php 文件,它将加载条带,而无需使用命名空间。这是我grabbed from here 的完整示例块。

    <?php
    require_once('vendor/autoload.php');
    
    $stripe = array(
      "secret_key"      => "sk_test_BQokikJOvBiI2HlWgH4olfQ2",
      "publishable_key" => "pk_test_6pRNASCoBOKtIshFeQd4XMUh"
    );
    
    \Stripe\Stripe::setApiKey($stripe['secret_key']);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 2015-05-13
      • 2017-10-23
      • 2021-08-02
      • 2017-09-12
      • 2017-09-14
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多