Search code examples
laravelinstagram-api

Saving an object into the session or cookie


I'm using Instagram API library to connect user to Instagram profile and then do smth with it. So, as Instagram API wiki says:

Once you have initialized the InstagramAPI class, you must login to an account.

$ig = new \InstagramAPI\Instagram(); 
$ig->login($username, $password); // Will resume if a previous session exists.

I have initialized InstagramAPI class and then I called $ig->login('username', 'password');. But I have to call it in every function where I need to work with Instagram.

So how could I save this object $ig for using it in the future in other controllers without calling login() any more? Can I save $ig object into the session or cookie file?

P.S. I think saving into the session is not safe way to solve the issue.

UPD: I was trying to save $ig object into the session, however the size is large and session become stop working as well.


Solution

  • Regarding the register method you asked in the comments section, all you need to create a new service provider class in your app\providers directory and declare the register method in there for example:

    namespace App\Providers;
    
    use InstagramAPI\Instagram;
    use Illuminate\Support\ServiceProvider;
    
    class InstagramServiceProvider extends ServiceProvider
    {
        public function register()
        {
            // Use singleton because, always you need the same instance
            $this->app->singleton(Instagram::class, function ($app) {
                return new Instagram();
            });
        }
    }
    

    Then, add your newly created InstagramServiceProvider class in providers array inside the config/app.php file for example:

    'providers' => [
        // Other ...
        App\Providers\InstagramServiceProvider::class,
    ]
    

    Now on, in any controller class, whenever you need the Instagram instance, all you need to call the App::make('InstagramAPI\Instagram') or simply call the global function app('InstagramAPI\Instagram') or even you can typehint the class in any method/constructor etc. Some examples:

    $ig = App::make('InstagramAPI\Instagram');
    $ig = App::make(Instagram::class); // if has use statement at the top fo the class
    $ig = app('...');
    

    In a class method as a dependency:

    public function someMethod(Instagram $ig)
    {
        // You can use $ig here
    }
    

    Hope this helps but read the documentation properly, there will get everything documented.