What is the best way to create Update Method using PHP OOP

时间:2015-10-30 22:34:19

标签: php oop

I have thinking of this from past an hour, but unable to understand the best way to add update, Insert feature using a class in PHP.

I have an employee table which has around 5 columns, so i have created different properties for it in my Employees Class.

Now i am unable to understand where to set these Values, in __costructor(), in add_employees() method or some other way..

If i set them in __constructor() then user must remember and follow the same pattern in writing arguments that i followed in writing the parameters.

I am unable to understand that is it a right way or should i use different approach to do this.

I have searched this on net, and found very complex examples, where people are taking argument in form of array, separating it, add loop in it and then put it into database.

Class Employees(){

    public $db;
    public $conn;
    public $emp_id;
    public $first_name;
    public $last_name;
    public $gender;
    public $added_by;

    public function __construct(){
        $this->db= new DatabaseConnection('localhost', 'root', '', 'employeesmanagement');
        $this->conn= $this->db->connectDb();            
    }

    public function get_employees(){

    }

    public function add_employees(){

    }

1 个答案:

答案 0 :(得分:2)

I've written a class before, that does only things related to database things. Here is the class

/**
 * CLASS: Database
 *
 * Description: This class deals with all database connection
 * across the website. If any class needs to use the database
 * it has to extends this one.
 *
 * @author: Andre Ferraz
 * @copyright: ^
 * @version: 2.0
 */
class Database
{
    /**
     * Holds Class Object instance
     *
     * @var Object
     * @access: Private
     * @static
     */
    private static $_instace;
    /**
     * Holds PDO Object
     *
     * @var PDO
     * @access: Private
     */
    private $_pdo;
    /**
     * Used to keep track of how many columns
     * has been found!
     *
     * @var int
     * @access: Private
     */
    private $_count;
    /**
     * Holds data from database
     *
     * @var array
     * @access: Private
     */
    private $_results = array();
    /**
     * Description: Instantiates PDO object
     *
     * @access: Protected
     */
    protected function __construct()
    {
        $host = Config::get("database:host");
        $user = Config::get("database:username");
        $pass = Config::get("database:password");
        $dbna = Config::get("database:dbname");
        try
        {
            $this->_pdo = new PDO("mysql:dbname=".$dbna.";host=".$host.";", $user, $pass);
        }
        catch(PDOException $e)
        {
            Redirect::to(500);
        }
    }
    /**
     * Description: Gets data from the database
     *
     * @access: protected
     * @return boolean
     */
    protected function get($table, $columns, $condition = null)
    {
        if($condition != null)
        {
            $query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
            if($query->execute())
            {
                $this->_count = $query->rowCount();
                if($this->_count > 0)
                {
                    $this->_results = $query->fetchAll();
                    return true;
                }
                return false;
            }
        }
        return false;
        //@todo condition == null
    }
    /**
     * Description: Very similar to get function, but
     * instead it just checks if data exists without storing
     * any data.
     *
     * @access: protected
     * @return boolean
     */
    protected function query($table, $columns, $condition = null)
    {
        if($condition != null)
        {
            $query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
            if($query->execute())
            {
                $this->_count = $query->rowCount();
                return(($this->_count > 0)? true : false);
            }
        }
        return false;
        //@todo condition == null
    }
    /**
     * Description: Updates information on the database
     *
     * @access: protected
     */
    protected function update($table, $CV = array(), $condition)
    {
        if($CV !=null)
        {
            $columns = '';
            $x = 1;
            foreach($CV as $key => $value)
            {
                $columns .= "$key='$value'";
                if($x < count($CV))
                {
                    $columns .= ",";
                }
                $x++;
            }
            $query = $this->_pdo->prepare("UPDATE $table SET $columns WHERE $condition");
            if($query->execute())
                return true;
            else
                return false;
        }
        return false;
    }
    /**
     * Description: Inserts data into database
     *
     * @access: protected
     */
    protected function insert($table, $CV = array())
    {
        if($CV !=null)
        {
            // Join array elements with a string
            $columns = implode(", ", array_keys($CV));
            $values = '';
            $x = 1;
            // Put array key values into variables
            foreach($CV as $value)
            {
                $values .= "'".$value."'";
                if($x < count($CV))
                {
                    $values .= ', ';
                }
                $x++;
            }
            $query = $this->_pdo->prepare("INSERT INTO $table ($columns) VALUES({$values})");
            // Check execution is successful
            if($query->execute())
                return true;
            else
                return false;
        }
        return false;
    }
    /**
     * Description: Deletes data from the database
     *
     * @access: protected
     */
    protected function delete($table, $condition = null)
    {
        if($condition != null)
        {
            $query = $this->_pdo->prepare("DELETE FROM $table WHERE $condition");
            if($query->execute())
                return true;
            else
                return false;
        }
        else
        {
            $query = $this->_pdo->prepare("DELETE FROM $table");
            if($query->execute())
                return true;
            else
                return false;
        }
    }
    protected function getResults()
    {
        return $this->_results;
    }
    /**
     * Description: Singleton pattern, prevents multiple
     * instantiations of the same class.
     *
     * NOTE: This is not needed. Only for "show of"
     *
     * @access: public
     * @static
     * @return Object
     */
    public static function instance()
    {
        if(isset(self::$_instace))
            return self::$_instace;
        else
            self::$_instace = new self;
    }
}

Which other classes like User class would extend and use all the necessary function from the database to get data related to the user. Have a look at the project. There are some bugs in a few classes (which I can't be bothered to fix at this point), but database class is working fine. I don't mind if you get reference from it.

Visit my github for the full project. Github