【问题标题】:Laravel 4 passing Controller $this to ServiceProviderLaravel 4 将 Controller $this 传递给 ServiceProvider
【发布时间】:2014-07-02 21:08:24
【问题描述】:

我想将$this 从我的Controller 传递给我的Service Provider,以便我可以将它与我的自定义类一起使用。这样,我可以引用我的控制器并输出成功。

控制器

function Foo(){

    //$this is defined
    MyFacade::Bar($input);

}

function success(){

     return var_dump('Succes!');

}

服务提供商

<?php namespace App\Libraries\Extensions\Filesystem;

use Illuminate\Support\ServiceProvider as  IlluminateServiceProvider;
use App\Libraries\Extensions\Filesystem\Filesystem;

class FilesystemServiceProvider extends IlluminateServiceProvider {

   public function register()
        { 
            $this->app->bind('files', function(){

               return new Filesystem($this);

            });    
    }
}

自定义类

<?php namespace App\Libraries\Extensions\Filesystem;

use \Illuminate\Filesystem\Filesystem as IlluminateFilesystem;

class Filesystem extends IlluminateFilesystem {

protected $listener;

    public function __construct($listener)
    {

        $this->listener = $listener;

    }

   function Bar($input){
     //Some code
     return $this->listener->Success();
   }

有了这个代码,我得到了Call to undefined method App\Libraries\Extensions\Filesystem\FilesystemServiceProvider::Success()

我相信我的Service Provider $this 被传递了,而不是我的Controller $this

如何将我的控制器 $this 传递给我的服务提供商,以便我可以调用 MyFacade::Bar($input)

【问题讨论】:

    标签: php laravel-4 this service-provider


    【解决方案1】:

    我想将 $this 从我的控制器传递给我的服务提供商,所以我 可以将它与我的自定义类一起使用。这样,我可以参考我的 控制器并输出成功。

    这是一个糟糕的主意,无论如何你都很难让它发挥作用。

    您的文件系统类应该不知道您的控制器类。传入 $this 并试图让 File 完成控制器的工作并不是这样做的方法。它应该只执行它的“文件”内容,然后返回适当的响应。

    控制器

    function Foo(){
    
        if (MyFacade::Bar($input))
        { 
            // Success
        }
        else
        {
            // Fail
        }
    
    }
    

    自定义类

    function Bar($input){
         //Some code
         return true; // or false
       }
    

    【讨论】:

    • 谢谢。这是一个很好的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2013-08-17
    • 2011-12-07
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多