Php 依赖注入问题
我读过关于依赖注入的书,我很了解它,现在我有一个小问题,我正在制作一个oop站点结构,它将包含很多类(成员、游戏、帖子等等)。 由于很多人告诉我,不建议为此使用全局变量,所以我遇到了这个小问题。例如:Php 依赖注入问题,php,global,Php,Global,我读过关于依赖注入的书,我很了解它,现在我有一个小问题,我正在制作一个oop站点结构,它将包含很多类(成员、游戏、帖子等等)。 由于很多人告诉我,不建议为此使用全局变量,所以我遇到了这个小问题。例如: $mysql_connection = ...connection $members = new Members($mysql_connection); //i need to implement posts and games $posts = new Posts($mysql_connect
$mysql_connection = ...connection
$members = new Members($mysql_connection); //i need to implement posts and games
$posts = new Posts($mysql_connection); //i need to implement members
$games = new Games($mysql_connection); //i need to implement members
当我使用全局变量传递类时,类的顺序并不那么重要:
global $connection;
$connection = ...connection
global $members;
$members = new Members();
global $posts;
$posts = new Posts();
etc...
类的示例:
class Posts{
function getMemberPosts($id){
...implementing the globals
global $connection, $members;
...using the globals
}
}
所以我的问题是,如果不使用globals,我如何做同样的事情?(不必是依赖项注入..)您希望存储和使用注入的组件,而不是全局组件
我不明白你的问题在哪里。您正确地创建了一个连接,并在实例化新类时将其注入到新类中。一切都好,不是吗?我不明白,OP也在试图做什么。
class Posts{
protected $dbconnection;
public function __construct($dbconn){
// save the injected dependency as a property
$this->dbconnection = $dbconn;
}
public function getMemberPosts($id, $members){
// also inject the members into the function call
// do something cool with members to build a query
// use object notation to use the dbconnection object
$this->dbconnection->query($query);
}
}