我知道这看起来像是Inject Silex $app in my custom class和其他人的重复,但我无法通过他们的解决方案来实现它。
我像这样定义我的服务:
$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
放在我的所有方法中,我怎么能做同样的事情呢?
答案 0 :(得分:5)
为什么不注射它?
$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;
}
}