Alias
Alias

Reputation: 3081

Laravel 4 - Declare class globally?

I'm using the package "Steam Condenser" in my Laravel 4 project. Once the user logs in to my application, I set a session with their ID (steamId). This ID can be used to grab various data (Name, Avatar etc), an example:

$steamUser = new SteamId( Session::get('steamId') );
$username = $steamUser->getNickname();

Now this works, however I'm going to be using this data on a lot of the pages (and also in the controllers). What I don't want to be doing is declaring a new class everytime - so my question is:

I see two ways of doing this:

  1. Via a __constructor, however I cannot get this to work (failing horribly).
  2. Via a route filter. So making a new filter name and for every route doing a 'before' => 'filter'. However this could become quite over excessive.

I hope this makes sense (my PHP knowledge isn't so great) - basically I don't want to do new SteamId( Session::get('steamId') ); all the time!

Upvotes: 2

Views: 2246

Answers (3)

Oddman
Oddman

Reputation: 3959

Use the IoC container, as mentioned by Dave Ganley. It allows you to define how an object is called/handled, and you simply resolve that class when the time comes, eg:

App::singleton('SteamId', function($app)
{
    return new SteamId(Session::get('steamId'));
});

Then when you need it, resolve it:

$steamIdObject = App::make('SteamId');

Will give you all methods for that class. And because it will act like a singleton - it will only ever be instantiated once.

In addition, you could tie this in with route filters and groups to ensure that this always gets called on every page, and sets the data you require. Then in your controllers, just call the same object via App::make and you're good to go :)

Upvotes: 6

Dave Ganley
Dave Ganley

Reputation: 416

Have a look at the IOC container http://four.laravel.com/docs/ioc

Upvotes: 1

Jake Wilson
Jake Wilson

Reputation: 91193

A constructor would be the most straightforward. If you tend to run the same code over and over in a class, then that's what the constructor is helpful for.

class WhateverController extends BaseController
{
  private $steamUser;
  private $data = array();

  public function __construct()
  {
    $this->steamUser = new SteamId(...);
    $data['steamUser'] = $this->steamUser;

    parent::__construct();
  }

  public function doSomething()
  {
    $nickname = $this->steamUser->getNickname();
    $something = Whatever:all();

    $this->data['something'] = $something;

    return View::make('myview', $this->data);

  }
}

You could always extend a custom base class controller as well.

Upvotes: 1

Related Questions