pgtips
pgtips

Reputation: 1338

class instantiation for use across all models in Laravel3

I am using Laravel 3 (new to it). I have an API helper class that I'm using as a library. I want to have that class instantiated so I can use it within all my models to access the API. I am struggling with figuring out how to do it without instantiating it once in each model. An example would be awesome. Thanks.

Upvotes: 0

Views: 85

Answers (2)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Use an IoC container.

Instantiate your class:

IoC::register('mailer', function()
{
    $transport = Swift_MailTransport::newInstance();

    return Swift_Mailer::newInstance($transport);
});

And then when you need to access your instance you just have to:

IoC::instance('mailer', $instance);

Reference: http://laravel.com/docs/ioc

Upvotes: 1

tplaner
tplaner

Reputation: 8461

There are a few ways you can go about doing this, the easiest would probably be just creating a base model where you instantiate the API helper class, then extending that base model for all of the models which you want to access the API.

It might look something like:

// base.php
class Base {

    public static function api()
    {
        return new YourApiClass;
    }

}

// user.php
class User extends Base {

    public static function name()
    {
        return parent::api()->callApiMethod();
    }

}

You could also use Laravel 3's IoC container, which might be the better choice depending on what you are doing.

Upvotes: 1

Related Questions