PHP Class. How to structure a method to save data

2019-08-04 19:55发布

问题:

I'm building a class to save data to the Database, but I'm without ideas on how to deal with this...

I have my project folders like this:

+Lib
+Models
    +Uddt
    -person.php
-uris.php
Main_class.php
Example_usage.php

The folder "Models" have the uris.php file that have methods to add and retrive information from the database tables.

The folder "Models\Uddt" have the User Defined Data Types that I have defined, for example, the person.php looks like this:

class Person {

    static $id_category = '2';

    public $uri;

    public $name;
    public $age;
    public $sex;
    public $address;
    public $country;

public function _Name() {
    // Connect the property name to the db name
    $db_name = 'name_in_db';

    // Some more code
}

public function _Age() {
    // Connect the property name to the db name
    $db_name = 'age_in_db';

    // Some more code
}

    public function save() {
        // do things to save the data to the database
    }

}

The database tables looks like this:

Table(uris_details)
uri             (PK FK)
id_category     (PK FK)
id_data_type    (PK FK)
n_text

Table(uris)
uri             (PK)
id_uri_state    (FK)

To insert the data to the database I want to use an object, just like this:

// Instantiate the object
$p = new Person;

// Add the values to the object
$p->uri     = 'http://www.fdsddd.com/gfd1';
$p->name    = 'John';
$p->age     = '27';
$p->sex     = 'Male';
$p->address = '10 Street';
$p->country = 'USA';

// Save the data to the database
$p->save(); 

The INSERTs will look like this:

INSERT INTO uris (uri, id_uri_state) VALUES ('http://www.fdsddd.com/gfd1', 'active');
INSERT INTO uris_details (uri, id_category, id_data_type, n_text) VALUES ('http://www.fdsddd.com/gfd1', '2', 'name_in_db', 'John');
INSERT INTO uris_details (uri, id_category, id_data_type, n_text) VALUES ('http://www.fdsddd.com/gfd1', '2', 'age_in_db', '27');
INSERT INTO uris_details (uri, id_category, id_data_type, n_text) VALUES ('http://www.fdsddd.com/gfd1', '2', 'sex_in_db', 'Male');
INSERT INTO uris_details (uri, id_category, id_data_type, n_text) VALUES ('http://www.fdsddd.com/gfd1', '2', 'address_in_db', '10 Street');
INSERT INTO uris_details (uri, id_category, id_data_type, n_text) VALUES ('http://www.fdsddd.com/gfd1', '2', 'country_in_db', 'USA');

My question:

How can I structure the "save()" method in the "Person" Class to save the data to the Database, any ideas? I must to do a transaction? I'm using PostgreSQL, shoul be better to create a PlPgSQL function to deal with the transaction?

Give me some clues.

Best Regards,