object oriented PHP and database wrappers

2019-08-12 12:29发布

问题:

I'm writing a small class for a booking system in PHP. By my own admission OOP is not my thing at all - but I'd like to use it for this project, assuming I can glean enough of an understanding to use it properly.

Here's some of what I have so far (mostly pseudo):

class bookingSystemDbWrapper
{
    public $db;
    function __construct()
    {
        $this->db = mysqli_connect(..., ..., ..., ...);    
    }
}

class bookingSystemAvailabilityManager extends bookingSystemDbWrapper
{
    function checkAvailability($date, $roomID)
    {
        /**
         * check availability for a given room on a given date 
         */

        $query = mysqli_real_escape_string("SELECT SOMETHING FROM SOMEWHERE");
        $result = mysqli_query($this->db, $query);
        return $result; 
    }        
}

This approach works fine for the small and simple classes above. But when I need a class for creating a booking, searching based on location, etc, it seems like a bad idea to be extending the database wrapper for every class. So I need another way to make my database wrapper class available to my other classes, so they can run database queries.

I've read up on dependency injection on nettuts here: http://net.tutsplus.com/tutorials/php/dependency-injection-huh/ but it's a bit beyond my limited understanding of OOP, so I'm unsure of what approach to take, or how to implement it correctly.

TL;DR

How should I make one classes' public vars available to other classes without breaking any principles of OOP, and keep my code readable?

回答1:

I suggest a static class, like this:

<?php
class dbms
    {
        const HOST     = 'localhost';
        const LOGIN    = 'login';
        const PASSWORD = 'myB!GevU1PwD';
        const SCHEMA   = 'mydb';
        const CHARSET  = 'utf8';
        const PORT     = 3306;

        protected static $instance;

        public static function connect()
            {
                if(is_object(static::$instance) && (static::$instance instanceof mysqli))
                    { return static::$instance->ping(); }

                static::$instance = new mysqli(static::HOST, static::LOGIN, static::PASSWORD, static::SCHEMA, static::PORT);

                if(static::$instance->connect_errno)return false;

                static::set_charset(static::CHARSET);
            }

        public static function disconnect()
            {
                static::$instance->close();

                static::$instance = null;
            }

        public static function &getInstance(){ return static::$instance; }
    }
?>

Should be easy-extendable, and seen everywhere you need:

  1. There is only one shared connection for static instance;
  2. It might be easy repurposed via extend without loosing performance;
  3. It accessible from everywhere you need, as it's a static class.