PHP code example of golossus / php-lazy-proxy-loading

1. Go to this page and download the library: Download golossus/php-lazy-proxy-loading library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

golossus / php-lazy-proxy-loading example snippets


use Golossus\LazyProxyLoading\ProxyClassFactory;
...
$myClassProxy = ProxyClassFactory::create(\MyClass::class, function () {
    return new \MyClass(/* dependencies */);
}); 

echo $myProxyClass->myClassPrublicMethod(); // MyClass service is created at this point
echo $myProxyClass->myClassPrublicMethod(); // MyClass service is already created at this point, so it's not re-built

..
use Illuminate\Support\ServiceProvider;
use Golossus\LazyProxyLoading\LazyLoadingTrait;
..

class MainProvider extends ServiceProvider
{
    use LazyLoadingTrait;

    public function register()
    {
        // common laravel service registration, not lazy
        $this->app->singleton(CustomMailingService::class, function () {
                $mailer = $this->app->make(Mailer::class);
                return new CustomMailingService($mailer);
            }
        );
    
        // or same service registration but lazy loaded
        $this->app->singleton(...$this->lazy(CustomMailingService::class, function () {
                $mailer = $this->app->make(Mailer::class);

                return new CustomMailingService($mailer);
            }
        ));
    }
}