Dependency Injection in Laravel 5 Package To Use or Not To Use

夙愿已清 提交于 2019-12-08 20:14:37

Facades provide a way of accessing the container through a class, so when you're accessing \Lang::function() you're actually calling app('translator')->function(). So in you're above example when you're binding the Lang facade into the container, you've then bound it twice, which isn't quite what you want.

All Laravel's functionality is already bound into the container and can be accessed by calling app('object'). You can see all the bindings here http://laravel.com/docs/5.0/facades

For dependency injection, you shouldn't be trying to inject the facades, but rather the classes the facades are already referencing. So for example, the \Lang facade references Illuminate\Translation\Translator which is bound to the container as translator

In your classes you can do the following

use App\Http\Controllers\Controller;
use Illuminate\Translation\Translator;

class MyController extends Controller
{
    protected $translator;

    // Dependency injection example
    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    public function index()
    {
        $text = $this->translator->get('package::all.text1');
    }

    // Method injection example
    public function myFunction(Translator $translator)
    {
        $text = $translator->get('package::all.text1');
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!