fishingboy/codeigniter-model-base

Codeigniter Model Base

Maintainers

Package info

github.com/fishingboy/Codeigniter-Model-Base

pkg:composer/fishingboy/codeigniter-model-base

Statistics

Installs: 21

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.1 2019-08-27 10:22 UTC

This package is auto-updated.

Last update: 2026-05-24 04:20:48 UTC


README

Packagist Version Downloads License: MIT

English | 繁體中文

Installation

composer require fishingboy/codeigniter-model-base

Requirements

  • CodeIgniter 3
  • Composer autoload enabled in your CodeIgniter application

Usage

If your table name is users, create the model file at application/models/Users_model.php.

<?php

use fishingboy\ci_model_base\CI_Model_base;

class Users_model extends CI_Model_base
{
    protected $table = "users";
}

Load the model before using it:

$this->load->model('Users_model', 'users_model');

Basic Operations

Find

Find records by a single field:

$users = $this->users_model->findBy('email', 'user@example.com');

Find records by multiple conditions:

$users = $this->users_model->findBy([
  'role' => 'admin',
  'status' => 'on'
]);

If the table has a status field, findBy() automatically adds status = 'on'.

Create

Create a record and return the inserted ID:

$id = $this->users_model->create([
  'title' => 'sample'
]);

If the table has created_at or updated_at fields, they are automatically set to NOW() when not provided.

Update

Update a record by primary key and return the updated ID:

$this->users_model->update($id, [
  'title' => 'sample'
]);

The default primary key is id. You can override it in your model:

protected $key = 'user_id';

Update by Conditions

Update records using custom conditions:

$this->users_model->updateWhere([
  'role' => 'member'
], [
  'status' => 'off'
]);

Delete by Conditions

Delete records using custom conditions:

$this->users_model->delete_where([
  'id' => $id
]);

Model Hooks

Override these methods in your model when you need custom validation or follow-up logic.

protected function verifyBeforeCreate(& $params)
{
    return $this->verifyParams($params, [
        'title' => 'required'
    ]);
}

protected function verifyBeforeUpdate(& $params)
{
    return true;
}

protected function verifyBeforeDelete(& $params)
{
    return true;
}

protected function afterCreate($id)
{
    return true;
}

Date Fields

For create(), update(), and updateWhere(), passing NOW() as a field value writes the database NOW() expression instead of a string.

$this->users_model->update($id, [
  'published_at' => 'NOW()'
]);

License

This package is open-sourced software licensed under the MIT license.