1

我知道对此打开了一些问题,但我需要一个更“具体”的示例
和解决方案。

这是我的示例
databse.class.php

class db{ 
   public function connect($conStr){...} 
} 

函数类.php

func class{ 
   public insert_song(){ 
      //ineed to use the conenct method from database 
      //then I would INERT INTO... 
   } 
}

问题:
1)我应该要求或扩展 func 类中的 db 类吗?
2)如果我需要,db类函数的范围会保留吗?(假设我在那里有一个私有变量,是否可以从外部访问它?)

4

3 回答 3

5
  • 不,您不应该要求或扩展数据库类。
  • 不,私有变量或方法永远不会在类之外可用。受保护的变量仅对子类可用,公共变量是……公共的。

您可能需要数据库类位于配置中某处的文件,因此您可以随时随地实例化数据库类。但是,由于您可能只需要一个数据库对象实例,您可以在配置中实例化它并使用Dependency injection传递它。

这基本上意味着您将数据库对象传递给需要一个的其他对象。处理数据库对象的一种常用方法是使用构造函数注入,尽管 setter 注入也可以。

您所做的与此类似:

// config:
$db = new Database;
$db->setConnectionValues();

$fooClass = new Foo($db);
$fooClass->insertSomething();

// fooClass:
class Foo
{
    private $db;

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

    public function insertSomething()
    {
        $this->db->query("INSERT");
    }
}

这解决了您的大部分依赖问题。

于 2012-07-11T08:01:53.767 回答
3
// changed the class name, func is not good for a class name.
class Foo {
   protected $db;

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

   public insert_song(){ 
      //ineed to use the conenct method from database 
      //then I would INERT INTO...
      $this->db->insert(...); 
   } 
}

例子:

// omited the error handling.
$db = new db();
$db->connect();
$foo = new Foo();
$foo->setDb($db);
$foo->insert_songs();
于 2012-07-11T07:58:38.670 回答
2

作为Abstraction的一部分,您应该分离类的职责。你的Database班级应该关心你的Songs(这是你应该如何命名的)班级。

如果您的Songs类使用Database该类,则应将其注入构造函数中,如下所示:

<?php

class Database {
    public function connect($conStr) {
        /*
         * Connect to database here
         */
    }
}

class Songs {
    private $db;
    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function insert_song($song) {
        /*
         * Now you can use $this->db as your database object!
         */
    }
}
于 2012-07-11T08:01:41.227 回答