Download the PHP package yidas/codeigniter-model without Composer
On this page you can find all versions of the php package yidas/codeigniter-model. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download yidas/codeigniter-model
More information about yidas/codeigniter-model
Files in yidas/codeigniter-model
Package codeigniter-model
Short Description CodeIgniter 3 ORM Base Model pattern with My_model example
License MIT
Homepage https://github.com/yidas/codeigniter-model
Informations about the package codeigniter-model
CodeIgniter Model
CodeIgniter 3 Active Record (ORM) Standard Model supported Read & Write Connections
This ORM Model extension is collected into yidas/codeigniter-pack which is a complete solution for Codeigniter framework.
FEATURES
-
ORM Model with Elegant patterns as Laravel Eloquent ORM & Yii2 Active Record
-
CodeIgniter Query Builder integration
-
Query Scopes support
- Read & Write Splitting for Replications
This package provide Base Model which extended CI_Model
and provided full CRUD methods to make developing database interactions easier and quicker for your CodeIgniter applications.
OUTLINE
- Demonstration
- Requirements
- Installation
- Configuration
- Defining Models
- Table Names
- Primary Keys
- Timestamps
- Database Connection
- Other settings
- Basic Usage
- Methods
- find()
- Query Builder Implementation
- reset()
- insert()
- batchInsert()
- update()
- batchUpdate()
- replace()
- delete()
- getLastInsertID()
- getAffectedRows()
- count()
- setAlias()
- Active Record (ORM)
- Inserts
- Updates
- Deletes
- Accessing Data
- Relationships
- Methods
- findone()
- findAll()
- save()
- beforeSave()
- afterSave()
- hasOne()
- hasMany()
- toArray()
- Soft Deleted
- Configuration
- Methods
- Query Scopes
- Configuration
- Methods
- Validation
- Validating Input
- validate()
- getErrors()
- Declaring Rules
- rules()
- Error Message with Language
- Filters
- Filters()
- Read & Write Connections
- Configuration
- Load Balancing for Databases
- Reconnection
- Pessimistic Locking
- Helpers
- indexBy()
DEMONSTRATION
ActiveRecord (ORM)
The pattern is similar to Yii2 Active Record and Laravel Eloquent
Find with Query Builder
Start to use CodeIgniter Query Builder from find()
method, the Model will automatically load its own database connections and data tables.
CRUD
REQUIREMENTS
This library requires the following:
- PHP 5.4.0+
- CodeIgniter 3.0.0+
INSTALLATION
Run Composer in your Codeigniter project under the folder \application
:
composer require yidas/codeigniter-model
Check Codeigniter application/config/config.php
:
You could customize the vendor path into
$config['composer_autoload']
CONFIGURATION
After installation, yidas\Model
class is ready to use. Simply, you could create a model to extend the yidas\Model
directly:
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 yidas\Model
instead.
Use My_model to Extend Base Model for every Models
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 yidas\Model
with configuration for fitting your common table schema:
2. Create each Model extended My_model
in application with its own table configuration:
3. Use each extended Model with library usages:
My_model Example with Document
DEFINING MODELS
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, 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:
You could set table alias by defining
protected $alias = 'A1';
for model.
Table Name Guessing Rule
In our pattern, The naming between model class and table is the same, with supporting no matter singular or plural names:
Model Class Name | Table Name |
---|---|
Post_model | post |
Posts_model | posts |
User_info_model | user_info |
Get Table Name
You could get table name from each Model:
Primary Keys
You may define a protected $primaryKey
property to override this convention:
Correct primary key setting of Model is neceesary for Active Record (ORM).
Timestamps
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
:
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:
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:
Also, you could customized turn timestamps behavior off for specified column by assigning as empty:
Database Connection
By default, all models will use the default database connection $this->db
configured for your application. If you would like to specify a different connection for the model, use the $database
property:
More Database Connection settings: Read & Write Connections
Other settings
BASIC USAGE
Above usage examples are calling Models out of model, for example in controller:
If you call methods in Model itself, just calling $this
as model. For example, $this->find()...
for find()
;
Methods
find()
Create an existent CI Query Builder instance with Model features for query purpose.
Example:
After starting
find()
from a model, it return originalCI_DB_query_builder
for chaining. The query builder could refer CodeIgniter Query Builder Class Document
Query Builder Implementation
You could assign Query Builder as a variable to handle add-on conditions instead of using $this->Model->getBuilder()
.
reset()
reset an CI Query Builder instance with Model.
Example:
insert()
Insert a row with Timestamps feature into the associated database table using the attribute values of this record.
Example:
batchInsert()
Insert a batch of rows with Timestamps feature into the associated database table using the attribute values of this record.
Example:
replace()
Replace a row with Timestamps feature into the associated database table using the attribute values of this record.
Example:
update()
Save the changes with Timestamps feature to the selected record(s) into the associated database table.
Example:
Notice: You need to call
update
from Model but not from CI-DB builder chain, the wrong sample code:
$this->Model->find()->where('id', 123)->update('table', ['status'=>'off']);
batchUpdate()
Update a batch of update queries into combined query strings.
Example:
delete()
Delete the selected record(s) with Timestamps feature into the associated database table.
Example:
getLastInsertID()
Get the insert ID number when performing database inserts.
Example:
getAffectedRows()
Get the number of affected rows when doing “write” type queries (insert, update, etc.).
Example:
count()
Get count from query
Example:
setAlias()
Set table alias
Example:
ACTIVE RECORD (ORM)
Active Record provides an object-oriented interface for accessing and manipulating data stored in databases. An Active Record Model class is associated with a database table, an Active Record instance corresponds to a row of that table, and an attribute of an Active Record instance represents the value of a particular column in that row.
Active Record (ORM) supported events such as timestamp for insert and update.
Inserts
To create a new record in the database, create a new model instance, set attributes on the model, then call the save
method:
Updates
The save
method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save
method:
Deletes
To delete a active record, call the delete
method on a model instance:
delete()
supports soft deleted and points to self if is Active Record.
Accessing Data
You could access the column values by accessing the attributes of the Active Record instances likes $activeRecord->attribute
, or get by array key likes $activeRecord['attribute']
.
Relationships
Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. This library makes managing and working with these relationships easy, and supports different types of relationships:
- One To One
- One To Many
To work with relational data using Active Record, you first need to declare relations in models. The task is as simple as declaring a relation method
for every interested relation, like the following,
Once the relationship is defined, we may retrieve the related record using dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
The dynamic properties' names are same as methods' names, like Laravel Eloquent
For Querying Relations, You may query the orders
relationship and add additional constraints with CI Query Builder to the relationship like so:
Methods
findOne()
Return a single active record model instance by a primary key or an array of column values.
Example:
findAll()
Returns a list of active record models that match the specified primary key value(s) or a set of column values.
Example:
Example of limit:
save()
Active Record (ORM) save for insert or update
beforeSave()
This method is called at the beginning of inserting or updating a active record
Example:
afterSave()
This method is called at the end of inserting or updating a active record
hasOne()
Declares a has-one relation
Example:
Accessing Relational Data:
hasMany()
Declares a has-many relation
Example:
Accessing Relational Data:
toArray()
Active Record transform to array record
Example:
It's recommended to use find() with CI builder instead of using ORM and turning it to array.
SOFT DELETED
In addition to actually removing records from your database, This Model can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at
attribute could be set on the model and inserted into the database.
Configuration
You could enable SOFT DELETED feature by giving field name to SOFT_DELETED
:
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:
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:
Methods
forceDelete()
Force Delete the selected record(s) with Timestamps feature into the associated database table.
Example:
restore()
Restore SOFT_DELETED field value to the selected record(s) into the associated database table.
Example:
withTrashed()
Without SOFT DELETED query conditions for next find()
Example:
QUERY SCOPES
Query scopes allow you to add constraints to all queries for a given model. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints. The SOFT DELETED scope is a own scope which is not includes in global scope.
Configuration
You could override _globalScopes
method to define your constraints:
After overriding that, the My_model
will constrain that scope in every query from find()
, unless you remove the query scope before a find query likes withoutGlobalScopes()
.
Methods
withoutGlobalScopes()
Without Global Scopes query conditions for next find()
Example:
withAll()
Without all query conditions (QUERY SCOPES) for next find()
That is, with all data set of Models for next find()
Example:
VALIDATION
As a rule of thumb, you should never trust the data received from end users and should always validate it before putting it to good use.
The ORM Model validation integrates CodeIgniter Form Validation that provides consistent and smooth way to deal with model data validation.
Validating Input
Given a model populated with user inputs, you can validate the inputs by calling the validate()
method. The method will return a boolean value indicating whether the validation succeeded or not. If not, you may get the error messages from getErrors()
method.
validate()
Performs the data validation with filters
ORM only performs validation for assigned properties.
Exmaple:
The methods of
yidas\Model
for modifying such asinsert()
andupdate()
will also perform validation. You can turn off$runValidation
parameter of methods if you ensure that the input data has been validated.
Exmaple of ORM Model:
A ORM model's properties will be changed by filter after performing validation. If you have previously called
validate()
. You can turn off$runValidation
ofsave()
for saving without repeated validation.
getErrors()
Validation - Get error data referenced by last failed Validation
Declaring Rules
To make validate()
really work, you should declare validation rules for the attributes you plan to validate. This should be done by overriding the rules()
method with returning CodeIgniter Rules.
rules()
Returns the validation rules for attributes.
Example:
The returning array format could refer CodeIgniter - Setting Rules Using an Array, and the rules pattern could refer CodeIgniter - Rule Reference
Error Message with Language
When you are dealing with i18n issue of validation's error message, you can integrate CodeIgniter language class into rules. The following sample code is available for you to implement:
In above case, the language file could be application/language/en-US/error_messages_lang.php
:
After that, the getErrors()
could returns field error messages with current language.
Filters
User inputs often need to be filtered or preprocessed. For example, you may want to trim the spaces around the username input. You may declare filter rules in filter()
method to achieve this goal.
In model's
validate()
process, thefilters()
will be performed beforerules()
is already be filtered.
To enable filters for validate()
, you should declare filters for the attributes you plan to perform. This should be done by overriding the filters()
method.
filters()
Returns the filter rules for validation.
Example:
The filters format:
[[['attr1','attr2'], callable],]
READ & WRITE CONNECTIONS
Sometimes you may wish to use one database connection for SELECT
statements, and another for INSERT
, UPDATE
, and DELETE
statements. This Model implements Replication and Read-Write Splitting, makes database connections will always be used while using Model usages.
Configuration
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:
Codeigniter DB Connection
It recommends to previously prepare CI DB connections, you could assign to attributes directly in construct section before parent's constrcut:
If you already have
$this->db
, it would be the default setting for both connection.This setting way supports Reconnection.
Codeigniter Database Key
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:
This method supports cache mechanism for DB connections, each model could define its own connections but share the same connection by key.
Codeigniter Database Config Array
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:
Load Balancing for Databases
In above case, you could set multiple databases and implement random selected connection for Read or Write Databases.
For example, configuring read databases in application/config/database
:
After that, you could use database key slave
to load or assign it to attribute:
Reconnection
If you want to reconnect database for reestablishing the connection in Codeigniter 3, for $this->db
example:
The model connections with Codeigniter DB Connection setting could be reset after reset the referring database connection.
Do NOT use
reconnect()
which is a useless method.
PESSIMISTIC LOCKING
The Model also includes a few functions to help you do "pessimistic locking" on your select
statements. To run the statement with a "shared lock", you may use the sharedLock
method to get a query. A shared lock prevents the selected rows from being modified until your transaction commits:
Alternatively, you may use the lockForUpdate
method. A "for update" lock prevents the rows from being modified or from being selected with another shared lock:
Example Code
This transaction block will lock selected rows for next same selected rows with FOR UPDATE
lock:
HELPERS
The model provides several helper methods:
indexBy()
Index by Key
Example: