douwu7563 2014-09-23 06:51
浏览 137
已采纳

在Laravel中将App对象传递给函数/类[重复]

I'm working with Laravel 4.2, calling a payment flow between form submit and the controller response. If the payment is accepted, a bunch of work is done behind the scene by the class 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 is on a different namespace, and I'm able to call a needed library using App::make

<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {

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

but, for testing purposes I want to remove all instantiations and calls to other classes directly from PaymentProcessor, so I've tried to do the following injection:

<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {
    private $app;

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

And tried:

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

But it leads to:

FatalErrorException (E_PARSE) syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

Am I in the right way?

Update:

I've also tried to call it as: $this->app->make

That leads to:

Call to undefined method Illuminate\Support\Facades\App::make()

</div>
  • 写回答

1条回答 默认 最新

  • doune1000 2014-09-23 07:16
    关注

    Probably you want to do something like that:

    something($app);
    
    function something (\Illuminate\Foundation\Application  $app) {
    
        echo  $app->getLocale();
    }
    

    So in your case you need to use $this->app->make syntax and you need to pass parameter as I showed (and $app is instance of \Illuminate\Foundation\Application not \App)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功