我如何使用$app在自定义类Silex


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

我知道这看起来像在我的自定义类和其他人中Inject Silex $app的副本,但我无法从他们的解决方案中获得它。

我这样定义我的服务:

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

我的类是这样的:

<?php
namespace MyApp'Repository;
use Silex'Application; 
class User {
    public function findAll(Application $app) {
        $users = $app['db']->fetchAll('SELECT * FROM user');
        return $users;
    }
}

我这样使用这个服务:

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

我怎么能做同样的事情没有把$app在我所有的方法?

你为什么不注射呢?

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

这是你修改过的类:

<?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;
    }
}

或者更好的做法是:只注入你真正需要的东西,而不是注入整个应用程序(这样就隐藏了你真正的依赖关系,使单元测试变得很痛苦):

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

这样你的类就变成:

<?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;
    }
}