将App对象传递给Laravel中的函数/类

时间:2014-09-23 06:51:33

标签: php laravel laravel-4 facade

我正在使用Laravel 4.2,在表单提交和控制器响应之间调用支付流程。如果付款被接受,则由PaymentProcessor类

在幕后完成一系列工作
use MyProject\libraries\payment\PaymentProcessor;

class MyFirstController extends \Controller {

    protected $paymentProcessor;

    public function __construct(
        PaymentProcessor $paymentProcessor
    ) {
        $this->paymentProcessor = $paymentProcessor;
    }

    public function postFormSubmit() {
        //DO SOME STUFF
        $paymentResult = $this->paymentProcessor->makePayment($paymentDetails);
    }
}

PaymentProcessor位于不同的命名空间,我可以使用App :: make

调用所需的库
<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {

    public function makePayment(PaymentDetails $paymentData) {
        $doFirstStep = \App::make('amazingLibrary')->doImportantThings();

但是,出于测试目的,我想直接从PaymentProcessor中删除所有实例化和调用其他类,所以我尝试进行以下注入:

<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {
    private $app;

    public function __construct(\App $app) {
        $this->app = $app;
    }

并尝试过:

    public function makePayment(PaymentDetails $paymentData) {
        $doFirstStep = $this->app::make('amazingLibrary')->doImportantThings();

但它导致:

FatalErrorException(E_PARSE)语法错误,意外的'::'(T_PAAMAYIM_NEKUDOTAYIM)

我是以正确的方式吗?

更新

我也尝试将其称为:$this->app->make

这导致:

调用未定义的方法Illuminate \ Support \ Facades \ App :: make()

1 个答案:

答案 0 :(得分:1)

可能你想做那样的事情:

something($app);

function something (\Illuminate\Foundation\Application  $app) {

    echo  $app->getLocale();
}

因此,在您的情况下,您需要使用$this->app->make语法,并且需要按照我显示的方式传递参数(并且$ app是\Illuminate\Foundation\Application的实例而不是\App