From 21e4b1bbf189fddeea4d4b22adab94ca77adba40 Mon Sep 17 00:00:00 2001 From: Nick Tsai Date: Sun, 31 Dec 2017 22:48:56 +0800 Subject: [PATCH] Release version 2.0.0 - Apply PSR-4 autoload method for lib namespace --- README.md | 66 +++++++++++++++++++------------- composer.json | 4 +- example/My_model.php | 44 ++++++++++----------- example/README.md | 37 ++++++++++++++++-- src/{BaseModel.php => Model.php} | 8 ++-- 5 files changed, 102 insertions(+), 57 deletions(-) rename src/{BaseModel.php => Model.php} (99%) diff --git a/README.md b/README.md index af88cd3..8626929 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ OUTLINE DEMONSTRATION ------------- -### Find one +### Find One ```php $this->load->model('post_model', 'PostModel'); @@ -79,6 +79,20 @@ $posts = $this->PostModel->find() ->result_array(); ``` +### CRUD +```php +$result = $this->PostModel->insert(['title' => 'Codeigniter Model']); +// Find out the record which just be inserted +$post = $this->PostModel->find() + ->order_by('id', 'DESC') + ->get() + ->row_array(); +// Update the record +$result = $this->PostModel->update(['title' => 'CI3 Model'], $post['id']); +// Delete the record +$result = $this->PostModel->delete($post['id']); +``` + --- INSTALLATION @@ -101,24 +115,24 @@ $config['composer_autoload'] = TRUE; CONFIGURATION ------------- -After installation, `\BaseModel` class is ready to use. Simply, you could create a model to extend the `BaseModel` directly: +After installation, `yidas\Model` class is ready to use. Simply, you could create a model to extend the `yidas\Model` directly: ```php -class Post_model extends BaseModel {} +class Post_model extends yidas\Model {} ``` After that, this model is ready to use for example: `$this->PostModel->findOne(123);` -However, the schema of tables such as primary key in your applicaiton may not same as default, and it's annoying to defind repeated schema for each model. We recommend you to make `My_model` to extend `BaseModel` instead. +However, the schema of tables such as primary key in your applicaiton may not same as default, and it's annoying to defind repeated schema for each model. We recommend you to make `My_model` to extend `yidas\Model` instead. -### Use My_model to Extend BaseModel for every Models +### Use My_model to Extend Base Model for every Models -You could use `My_model` to extend `BaseModel`, then make each model to extend `My_model` in Codeigniter application. +You could use `My_model` to extend `yidas\Model`, then make each model to extend `My_model` in Codeigniter application. -*1. Create `My_model` extended `BaseModel` with configuration for fitting your common table schema:* +*1. Create `My_model` extended `yidas\Model` with configuration for fitting your common table schema:* ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $primaryKey = 'sn'; const CREATED_AT = 'created_time'; @@ -151,14 +165,14 @@ $post = $this->PostModel->findOne(123); Defining Models --------------- -To get started, let's create an model extends `BaseModel` or through `My_model`, then define each model suitably. +To get started, let's create an model extends `yidas\Model` or through `My_model`, then define each model suitably. ### Table Names -By convention, the "snake case" with lowercase excluded `_model` postfix of the class name will be used as the table name unless another name is explicitly specified. So, in this case, BaseModel will assume the `Post_model` model stores records in the `post` table. You may specify a custom table by defining a table property on your model: +By convention, the "snake case" with lowercase excluded `_model` postfix of the class name will be used as the table name unless another name is explicitly specified. So, in this case, Model will assume the `Post_model` model stores records in the `post` table. You may specify a custom table by defining a table property on your model: ```php -// class My_model extends BaseModel +// class My_model extends yidas\Model class Post_model extends My_model { protected $table = "post_table"; @@ -182,7 +196,7 @@ In our pattern, The naming between model class and table is the same, with suppo You may define a protected `$primaryKey` property to override this convention: ```php -class My_model extends BaseModel +class My_model extends yidas\Model {    protected $primaryKey = "sn"; } @@ -190,10 +204,10 @@ class My_model extends BaseModel ### Timestamps -By default, BaseModel expects `created_at` and `updated_at` columns to exist on your tables. If you do not wish to have these columns automatically managed by BaseModel, set the `$timestamps` property on your model as `false`: +By default, Model expects `created_at` and `updated_at` columns to exist on your tables. If you do not wish to have these columns automatically managed by base Model, set the `$timestamps` property on your model as `false`: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $timestamps = false; } @@ -202,7 +216,7 @@ class My_model extends BaseModel If you need to customize the format of your timestamps, set the `$dateFormat` property on your model. This property determines how date attributes are stored in the database: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { /** * Date format for timestamps. @@ -216,7 +230,7 @@ class My_model extends BaseModel If you need to customize the names of the columns used to store the timestamps, you may set the `CREATED_AT` and `UPDATED_AT` constants in your model: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { const CREATED_AT = 'created_time'; const UPDATED_AT = 'updated_time'; @@ -226,7 +240,7 @@ class My_model extends BaseModel Also, you could customized turn timestamps behavior off for specified column by assigning as empty: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { const CREATED_AT = 'created_time'; const UPDATED_AT = NULL; @@ -362,7 +376,7 @@ In addition to actually removing records from your database, This Model can also You could enable SOFT DELETED feature by giving field name to `SOFT_DELETED`: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { const SOFT_DELETED = 'is_deleted'; } @@ -371,7 +385,7 @@ class My_model extends BaseModel While `SOFT_DELETED` is enabled, you could set `$softDeletedFalseValue` and `$softDeletedTrueValue` for fitting table schema. Futher, you may set `DELETED_AT` with column name for Timestapes feature, or disabled by setting to `NULL` by default: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { const SOFT_DELETED = 'is_deleted'; @@ -388,7 +402,7 @@ class My_model extends BaseModel If you need to disabled SOFT DELETED feature for specified model, you may set `SOFT_DELETED` to `false`, which would disable any SOFT DELETED functions including `DELETED_AT` feature: ```php -// class My_model extends BaseModel +// class My_model extends yidas\Model class Log_model extends My_model { const SOFT_DELETED = false; @@ -449,7 +463,7 @@ Query scopes allow you to add constraints to all queries for a given model. Writ You could override `_globalScopes` method to define your constraints: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $userAttribute = 'uid'; @@ -499,7 +513,7 @@ Sometimes you may wish to use one database connection for `SELECT` statements, a ### Configuration -Read & Write Connections could be set in the model which extends `BaseModel`, you could defind the read & write databases in extended `My_model` for every models. +Read & Write Connections could be set in the model which extends `yidas\Model`, you could defind the read & write databases in extended `My_model` for every models. There are three types to set read & write databases: @@ -509,7 +523,7 @@ There are three types to set read & write databases: You could set the database key refered from `\application\config\database.php` into model attributes of `database` & `databaseRead`, the setting connections would be created automatically: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $database = 'default'; @@ -524,7 +538,7 @@ class My_model extends BaseModel If you already have prepared CI DB connections, you could assign to attributes directly in construct section before parent's constrcut: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { function __construct() { @@ -542,7 +556,7 @@ class My_model extends BaseModel This way is used for the specified model related to the one time connected database in a request cycle, which would create a new connection per each model: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $databaseRead = [ 'dsn' => '', @@ -567,7 +581,7 @@ $db['slave']['hostname'] = $slaveHosts[mt_rand(0, count($slaveHosts) - 1)]; After that, you could use database key `slave` to load or assign it to attribute: ```php -class My_model extends BaseModel +class My_model extends yidas\Model { protected $databaseRead = 'slave'; } diff --git a/composer.json b/composer.json index 26b51cd..1bcb61e 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,8 @@ }, "minimum-stability": "stable", "autoload": { - "classmap": ["src/"] + "psr-4": { + "yidas\\": "src/" + } } } diff --git a/example/My_model.php b/example/My_model.php index dbcd5b5..0019d18 100644 --- a/example/My_model.php +++ b/example/My_model.php @@ -3,17 +3,21 @@ /** * My_model * - * Based on BaseModel, My_model is customized for your web application with features, such as the - * verification of user ID and company ID for multiple user layers. + * Based on yidas\Model, My_model is customized for your web application with schema such as + * primary key and column names for behavior setting. Futher, all of your model may need access + * features, such as the verification of user ID and company ID for multiple user layers. + * * This example My_model assumes that a user is belong to a company, so each data row is belong to * a user with that company. The Model basic funcitons overrided BaseModel with user and company * verification to implement the protection. * * @author Nick Tsai + * @version 2.0.0 + * @see https://github.com/yidas/codeigniter-model/tree/master/example + * @since \yidas\Mdoel 2.0.0 * @see https://github.com/yidas/codeigniter-model - * @since BaseMdoel 0.15.0 */ -class My_model extends BaseModel +class My_model extends yidas\Model { /* Configuration by Inheriting */ @@ -35,7 +39,7 @@ class My_model extends BaseModel protected $dateFormat = 'unixtime'; // Record status for checking is deleted or not - const RECORD_DELETED = 'is_deleted'; + const SOFT_DELETED = 'is_deleted'; // 0: actived, 1: deleted protected $recordDeletedFalseValue = '1'; @@ -111,7 +115,7 @@ protected function _globalScopes() $this->getBuilder()->where( $this->_field($this->companyAttribute), - $this->$companyID + $this->companyID ); } @@ -122,58 +126,50 @@ protected function _globalScopes() $this->userID ); } - return parent::_globalScopes(); } - /** * Override _attrEventBeforeInsert() */ protected function _attrEventBeforeInsert(&$attributes) { // Auto Company - if ($this->companyAttribute && !isset($attr[$this->companyAttribute])) { + if ($this->companyAttribute && !isset($attributes[$this->companyAttribute])) { - $attributes[$this->companyAttribute] = $this->companySN; + $attributes[$this->companyAttribute] = $this->companyID; } - // Auto User - if ($this->userAttribute && !isset($attr[$this->userAttribute])) { + if ($this->userAttribute && !isset($attributes[$this->userAttribute])) { - $attributes[$this->userAttribute] = $this->userSN; + $attributes[$this->userAttribute] = $this->userID; } - // Auto created_by - if ($this->createdUserAttribute) { - $attributes[$this->createdUserAttribute] = $this->userSN; + if ($this->createdUserAttribute && !isset($attributes[$this->createdUserAttribute])) { + $attributes[$this->createdUserAttribute] = $this->userID; } return parent::_attrEventBeforeInsert($attributes); } - /** * Override _attrEventBeforeUpdate() */ public function _attrEventBeforeUpdate(&$attributes) { // Auto updated_by - if ($this->updatedUserAttribute) { - $attributes[$this->updatedUserAttribute] = $this->userSN; + if ($this->updatedUserAttribute && !isset($attributes[$this->updatedUserAttribute])) { + $attributes[$this->updatedUserAttribute] = $this->userID; } - return parent::_attrEventBeforeUpdate($attributes); } - /** * Override _attrEventBeforeDelete() */ public function _attrEventBeforeDelete(&$attributes) { // Auto deleted_by - if ($this->deletedUserAttribute) { - $attributes[$this->deletedUserAttribute] = $this->userSN; + if ($this->deletedUserAttribute && !isset($attributes[$this->deletedUserAttribute])) { + $attributes[$this->deletedUserAttribute] = $this->userID; } - return parent::_attrEventBeforeDelete($attributes); } } diff --git a/example/README.md b/example/README.md index 0572b1c..ee1e45e 100644 --- a/example/README.md +++ b/example/README.md @@ -1,11 +1,11 @@ Example of My_model =================== -You could make My_model extends `BaseModel` for each model in your application. +The best practice to use `BaseModel` is using `My_model` to extend for every models, you could refer the document [Use My_model to Extend BaseModel for every Models](https://github.com/yidas/codeigniter-model#use-my_model-to-extend-basemodel-for-every-models) for building the structure in your Codeigniter application. -Example of [My_model](https://github.com/yidas/codeigniter-model/blob/master/example/My_model.php): +[My_model example code](https://github.com/yidas/codeigniter-model/blob/master/example/My_model.php) ->Based on BaseModel, My_model is customized for your web application with features, such as the verification of user ID and company ID for multiple user layers. +>Based on BaseModel, My_model is customized for your web application with schema such as primary key and column names for behavior setting. Futher, all of your model may need access features, such as the verification of user ID and company ID for multiple user layers. --- @@ -14,6 +14,37 @@ Features This example My_model assumes that a user is belong to a company, so each data row is belong to a user with that company. The Model basic funcitons overrided BaseModel with user and company verification to implement the protection. +--- + +CONFIGURATION +------------- + +```php +class My_model extends BaseModel +{ + /* Configuration by Inheriting */ + + // The regular PK Key in App + protected $primaryKey = 'id'; + // Timestamps on + protected $timestamps = true; + // Soft Deleted on + const SOFT_DELETED = 'is_deleted'; + + protected function _globalScopes() + { + // Global Scope... + } + + protected function _attrEventBeforeInsert(&$attributes) + { + // Insert Behavior... + } + + // Other Behaviors... +} +``` + Defining Models --------------- diff --git a/src/BaseModel.php b/src/Model.php similarity index 99% rename from src/BaseModel.php rename to src/Model.php index 67fb84b..8e5c36c 100644 --- a/src/BaseModel.php +++ b/src/Model.php @@ -1,13 +1,15 @@ - * @version 1.1.1 + * @version 2.0.0 * @see https://github.com/yidas/codeigniter-model */ -class BaseModel extends CI_Model +class Model extends \CI_Model { /** * Database Configuration for read-write master @@ -35,7 +37,7 @@ class BaseModel extends CI_Model * * @var string Field name of single column primary key */ - protected $primaryKey = ''; + protected $primaryKey = 'id'; /** * @string Feild name for created_at, empty is disabled.