PHP: Database Connection Class Constructor Method

前端 未结 6 1013
旧巷少年郎
旧巷少年郎 2021-02-03 16:19

I\'m new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was t

6条回答
  •  盖世英雄少女心
    2021-02-03 16:54

    Well, it's not going to run quite yet. You need to change your variables so that they match your connection params:

    $dbHost = "localhost";
    

    Should be

    $this->dbHost = 'localhost';
    

    I normally don't put my login params inside of the class at all. I would pass them into the constructor when the object is created. Use an outside config file so you can actually use this class on more than one build. :)

    Update::

    Okay, so here are a few little OOP configuration gold-nuggets that help you build a dynamic Database class.

    • Check out http://redbeanphp.com/ It will allow you to do a psuedo ORM style of data modelling. Super easy to install, and ridiculously easy to get your database up and running. http://redbeanphp.com/manual/installing

    • Create a configuration file that contains things like constants, template setups, common functions, and an AUTOLOADER Configuration files are key when working in version controlled environments. :)

    • Build your Database class as an abstract class http://php.net/manual/en/language.oop5.abstract.php

      abstract class Database
      {
        public function update()
        {
        }
      
        public function deactivate()
        {
        }
      
        public function destroy()
        {
        }
      
        //etc.
      }
      
      class MyAppObject extends Database
      {
      }
      
    • Put all of your class files into a library folder, and then put your configuration file into that library. Now, to make your life easier you can use an autoloader function to bring your classes to life whenever you need them, without having to include any specific class. See below:

      //note: this is never explicitly instantiated
      //note: name your files like this: MyAppObject.class.php  
      function my_fancypants_autoloader( $my_class_name )
      {
        if( preg_match( "%^_(Model_)%", $my_class_name ) ) return;
        require_once( "$my_class_name.class.php" );
      }
      spl_autoload_register( 'my_fancypants_autoloader' );
      
      • Now all you have to do is include one configuration file in your .php files to access your classes.

    Hope that points you in the right direction! Good luck!

提交回复
热议问题