Jump to content

Database Abstract Class, MySQL Child Class, passing login details


MasterACE14

Recommended Posts

Good day,

 

I have an Abstract 'Database' class and a 'MySQL' child class. Currently I'm passing the host, username, password and database name through the MySQL class constructor. Is there a better way of passing the login details to the 'MySQL' child class, whether it is through the Abstract class? or another way?

 

Thanks,

Ace

Link to comment
Share on other sites

expanding on your example from yesterday thorpe, if I have the __construct() in Class 'A', when Class A is instantiated and passed to the User class, I need to pass $host, $user, $pass, $dbname everytime Class A is passed to a class? or is there a better/different way of doing this?

 

Abstract class Foo {
  public function bar() {}
}

class User {
  private $foo;
  public function __construct(Foo $foo) {
    $this->foo = $foo;
  }
  public function something() {
    echo $this->foo->bar();
  }
}

class A extends Foo {
  private $host, $user, $pass, $dbname;
  public function __construct($host,$user,$pass,$dbname) {
    $this->host = $host;
    $this->user = $user;
    $this->pass = $pass;
    $this->dbname = $dbname;
  }

  public function bar() {
    return 'this is A::bar()';
  }
}


}

$user1 = new User(new A('localhost','root','pass','db'));

Link to comment
Share on other sites

You can simply an instance and then pass it to User (which is what you are already doing anyway). This way it's easier if you need to use A in multiple objects.

 

$a = new A('localhost','root','pass','db');
$user1 = new User($a);

 

This is generally the simplest option. The above example is dependency injects at it's simplest. There are however more flexible (and more complex) patterns you can use. Google 'PHP Dependency Injection' and you should find some tutorials. There is also a decent library floating around these days from the guys who wrote Symfony. It's well worth taking a look at even if you don't end up using it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.