Aram Boyajyan
Aram Boyajyan

Reputation: 844

Slim PHP: make $app available in classes

I'm using controller/method as callbacks to application routes.

E.g.:

$app->get('/user/login', array('User', 'login'));

Here is the sample User class:

Class User {
  public function login() {
    print 'Login page.';
  }
}

How can I make the $app variable available automatically in all classes?
I know I can get it using getInstance() method, but I need to call it manually every time.

Thanks!

Upvotes: 1

Views: 4170

Answers (2)

Werner
Werner

Reputation: 3663

Edit: Sorry, only saw your note about not wanting to call getInstance() afterwards. I'll leave my initial answer here as reference in either case.

You can simply call the getInstance() method: $app = \Slim\Slim::getInstance();

Since November 2013 you may now use a controller class instance as a callback for your Slim app routes (and their parameters) via functionality called "Class Controllers":

$app->map('/foo/:bar/:baz', '\Foo:fun')->via('GET', 'POST');

Getting an instance of $app in the callback class instance is easy enough:

class Foo {
    public function fun($var1, $var2) {
        $app = \Slim\Slim::getInstance();
    }
}

Upvotes: 1

George Cummins
George Cummins

Reputation: 28936

Create a base class that provides common elements and extend that base class in each of your controllers. Here is an example base class:

class BaseController { 
   $app = new YourApp();

    function __construct() {
           $this->app->get('/user/login', array('User', 'login'));

}

Then, you can extend that class you your controller to get access to $app:

class User extends BaseController {

    function yourFunction() {
        // $this->app is already set!
}

Update to parameterize the route:

In BaseController:

function __construct($route) {
       $this->app->get($route, array('User', 'login'));

Then include the route parameter when you initialize your class:

$user = new User('/user/login');

Upvotes: 3

Related Questions