twharmon
twharmon

Reputation: 4272

How can I use $app in custom classes in Silex?

I know this looks like a dupllicate of Inject Silex $app in my custom class and others, but I couldn't get it working from their solutions.

I define my service like this:

$app['user.repo'] = function () {
    return new MyApp\Repository\User();
};

My class looks like this:

<?php
namespace MyApp\Repository;
use Silex\Application; 

class User {
    public function findAll(Application $app) {
        $users = $app['db']->fetchAll('SELECT * FROM user');
        return $users;
    }
}

And I use the service like this:

$users = $app['user.repo']->findAll($app);

How can I do this same thing without putting $app in all my methods?

Upvotes: 1

Views: 460

Answers (1)

Maerlyn
Maerlyn

Reputation: 34107

Why don't you inject it?

$app['user.repo'] = function () use ($app) {
    return new MyApp\Repository\User($app);
};

And here's your modified class:

<?php

namespace MyApp\Repository;
use Silex\Application; 

class User {
    /** @var Application */
    protected $app;

    public function __construct(Application $app) {
        $this->app = $app;
    }

    public function findAll() {
        $users = $app['db']->fetchAll('SELECT * FROM user');

        return $users;
    }
}

Or even better: instead of injecting the whole application (and thus hiding your real dependencies, making unit testing a pain), only inject what you really need:

$app['user.repo'] = function () use ($app) {
    return new MyApp\Repository\User($app["db"]);
};

This way your class becomes:

<?php

namespace MyApp\Repository;
use Silex\Application; 

class User {
    protected $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function findAll() {
        $users = $this->db->fetchAll('SELECT * FROM user');

        return $users;
    }
}

Upvotes: 6

Related Questions