Php framework Yaf Pdo encapsulation class and ORM integration method

Source: Internet
Author: User

The Yaf PDO encapsulation class of php framework is integrated with ORM. yaf itself does not contain orm data encapsulation. We can implement our own encapsulation on pdo.

I. First, we use the php Singleton mode to create a base class. Library \ Base. php

<? Php
 
Class Base {
 
/**
* Singleton mode in design mode
* $ _ Instance must be declared as a static private variable
*/
// Save the instance in this attribute
Private static $ _ instance;
 
// Singleton method
Public static function getInstance (){
 
$ Class_name = get_called_class ();
If (! Isset (self ::$ _ instance [$ class_name]) {
 
Self: $ _ instance [$ class_name] = new $ class_name;
}
 
/* @ Var $ class_name */
Return self: $ _ instance [$ class_name];
}
 
// Prevents users from copying object instances
Public function _ clone (){
Trigger_error ('Clone is not allow', E_USER_ERROR );
}
 
}

II. Take the registered user information as an example. $ userInfo is the data passed in the form. We want to insert it into the database.

We have created the userModel class.

Class userModel extends Model {
 
}
 
$ Uid = userModel: getInstance ()-> add ($ userInfo );
We use the add method to insert data. We need to create this method in the Model.

III. Integrate ORM into library \ Model. php

<? Php
 
Class Model extends Base {
 
// Primary key name
Public $ primaryKey = 'id ';
Public $ orderKey = 'id ';
// Data table field name => initial value
Public $ fileds = array ();
// Write-only cache
Protected $ onlyCache = false;
// Data table name
Protected $ table;
Protected $ readDb = false;
Protected $ cacheObj;
Protected $ dbObj;
 
 
 
Function _ construct (){
$ This-> init ();
}
 
Public function init (){
$ This-> table = str_replace ('model', '', get_called_class ());
$ This-> dbObj = Db_Pdo: getInstance ();
 
// Import db configuration
$ Config = Common: getConfig ('database ');
 
$ This-> dbObj-> loadConfig ($ config );
}
 
 
 
/**
* Add data
* @ Param type $ parmas
* @ Return type
*/
Public function add ($ parmas ){
If (! $ Parmas |! Is_array ($ parmas ))
Return false;
 
$ Parmas = $ this-> initFields ($ parmas );
 
If (! $ Parmas)
Return false;
 
$ Time = date ("Y-m-d H: I: s ");
$ Parmas ['create _ time'] = $ time;
$ Parmas ['update _ time'] = $ time;
$ Id = $ this-> insertDB ($ parmas );
 
If (! $ Id ){
Return false;
}
 
Return $ id;
}
 
}
 
/**
* Db added
* @ Param type $ parmas
* @ Return boolean
*/
Private function insertDB ($ parmas ){
 
If ($ this-> onlyCache ){
Return true;
}
 
If (! $ Parmas |! Is_array ($ parmas )){
Return false;
}
 
$ Ret = $ this-> dbObj-> insert ($ this-> table, $ parmas );
 
Return $ ret;
}

We initialized the db configuration, referenced the pdo operation class, and executed the pdo data insertDB operation in the add method.

4. Finally, we need to define the insert method in the pdo operation class to execute the final insert library/Db/Pdo. php

<? Php
 
Class Db_Pdo {
 
Protected static $ instance = null;
 
Public static $ TIMESTAMP_WRITES = false;
 
Public static function getInstance (){
If (! Isset (self: $ instance )){
Self: $ instance = new self ();
}
Return self: $ instance;
}
 
Public function loadConfig ($ db ){
$ This-> configMaster ($ db ['M'] ['host'], $ db ['M'] ['name'], $ db ['M'] ['user'], $ db ['M'] ['pwd'], $ db ['M'] ['port']);
$ This-> configSlave ($ db ['s '] ['host'], $ db ['s'] ['name'], $ db ['s '] ['user'], $ db ['s'] ['pwd'], $ db ['s '] ['port']);
}
 
Public function insert ($ table, $ params = array (), $ timestamp_this = null, $ break = false ){
If (is_null ($ timestamp_this )){
$ Timestamp_this = self: $ TIMESTAMP_WRITES;
}
 
// First we build the SQL query string
$ Columns_str = '(';
$ Values_str = 'values (';
$ Add_comma = false;
 
// Add each parameter into the query string
Foreach ($ params as $ key => $ val ){
// Only add comma after the first parameter has been appended
If ($ add_comma ){
$ Columns_str. = ',';
$ Values_str. = ',';
} Else {
$ Add_comma = true;
}
 
// Now append the parameter
$ Columns_str. = "$ key ";
$ Values_str. = ": $ key ";
}
 
// Add the timestamp columns if neccessary
If ($ timestamp_this === true ){
$ Columns_str. = ($ add_comma? ',': ''). 'Date _ created, date_modified ';
$ Values_str. = ($ add_comma? ',': ''). Time (). ','. time ();
}
 
// Close the builder strings
$ Columns_str. = ')';
$ Values_str. = ')';
 
// Build final insert string
$ SQL _str = "INSERT INTO $ table $ columns_str $ values_str ";
If ($ break ){
Return $ SQL _str;
}
// Now we attempt to write this row into the database
Try {
$ Pstmt = $ this-> getMaster ()-> prepare ($ SQL _str );
 
// Bind each parameter in the array
Foreach ($ params as $ key => $ val ){
$ Pstmt-> bindValue (':'. $ key, $ val );
}
 
$ Pstmt-> execute ();
$ NewID = $ this-> getMaster ()-> lastInsertId ();
 
// Return the new id
Return $ newID;
} Catch (PDOException $ e ){
If (self: $ SHOW_ERR = true ){
Throw new Exception ($ e );
}
$ This-> pdo_exception = $ e;
Return false;
} Catch (Exception $ e ){
If (self: $ SHOW_ERR = true ){
Throw new Exception ($ e );
}
$ This-> pdo_exception = $ e;
Return false;
}
}
 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.