laravel-localization icon indicating copy to clipboard operation
laravel-localization copied to clipboard

Support contextual binding

Open jordyvanderhaegen opened this issue 10 months ago • 2 comments

Hi, this PR adds support for contextual binding in Laravel.

This comes in handy when you want to inject a different implementation into the LaravelLocalization class.

A quick example: We have extended Laravel's translations loader to support loading translations from the database. We have done so by overwriting the app('translator') in the container. However, to improve performance we would like to only load translations from the filesystem when using this package. Before this PR, there was no way to tell Laravel that the LaravelLocalization class can only use the file loader. After this PR, we can now tell Laravel to inject the file loader instance when it is requested by the LaravelLocalization class:

        $this
            ->app
            ->when(LaravelLocalization::class)
            ->needs(Translator::class)
            ->give(function (Application $app) {
                $loader = new FileLoader($app['files'], [__DIR__.'/lang', $app['path.lang']]);

                return new Translator($loader, $app->getLocale());
            });

What has been changed in this PR?

  • The LaravelLocalization class now uses depedency injection to retrieve instances from the container. This looks like a breaking change since the constructor has been altered.
  • The $view class property has been removed, since it was not used anywhere.

What tests have been changed in this PR?

  • All places where a new instance of the LaravelLocalization class was created has been changed to now retrieve the instance from the container instead.

jordyvanderhaegen avatar Aug 09 '23 18:08 jordyvanderhaegen

Can you add this changes to the changelog and how to fix any breaking changes? I'll create a version 2.0.0 of the package with your changes.

mcamara avatar Aug 11 '23 10:08 mcamara

Done, included the upgrade process in a new UPGRADING.md file

jordyvanderhaegen avatar Aug 11 '23 13:08 jordyvanderhaegen

I'll merge this now and create version 2.0 of the package alongside laravel 11 update

mcamara avatar Mar 13 '24 08:03 mcamara