0% found this document useful (0 votes)
25 views8 pages

Chapter 8 - CodeIgniter Models

This document provides an overview of models in CodeIgniter, including desired learning outcomes, model concepts, database environment setup, queries, and model creation. It discusses that models represent database tables, are responsible for data storage and retrieval, and provide abstraction from the database. It also provides steps for creating a model class, configuring model properties, and accessing models from controllers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views8 pages

Chapter 8 - CodeIgniter Models

This document provides an overview of models in CodeIgniter, including desired learning outcomes, model concepts, database environment setup, queries, and model creation. It discusses that models represent database tables, are responsible for data storage and retrieval, and provide abstraction from the database. It also provides steps for creating a model class, configuring model properties, and accessing models from controllers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES

TAGUIG CAMPUS CodeIgniter Models


Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

DESIRED LEARNING OUTCOMES (DLO)

- Understand the concept of Models in CodeIgniter framework.


- Set up the database environment in CodeIgniter.
- Configure the database connection in CodeIgniter.
- Create Models in CodeIgniter.
- Use Models to interact with the database.
- Create, read, update and delete records from the database using Models.

CODEIGNITER MODELS OVERVIEW

- Models are responsible for interacting with the database or other data storage mechanisms to retrieve, store,
update, and delete data.
- Models in CodeIgniter are PHP classes that represent the data and business logic of an application.
- Models help to keep the business logic and database interactions of an application organized and
maintainable.
- By separating these concerns into distinct classes, developers can more easily manage the complexity of their
applications and ensure that changes to the data layer do not affect the business logic.
- Models provide a layer of abstraction between the application code and the database.
- This allows developers to write database-independent code that can be used with different database
management systems.

DATABASE ENVIRONMENT SETUP

- There are 2 ways to connect to the Database.


1. Database.php file
o The file is located in app/Config/Database.php
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

2. .env file
o The file is located in the root folder of the CodeIgniter Project and is named env.
o Rename the file from env to .env

database.tests.hostname = localhost
database.tests.database = ci4_test
database.tests.username = root
database.tests.password = root
database.tests.DBDriver = MySQLi
database.tests.DBPrefix =
database.tests.port = 3306

- [Database.php] You can connect to your database by adding this line of code in any function where it is
needed, or in your class constructor to make the database available globally in that class.

$db = \Config\Database::connect();

- While CodeIgniter intelligently takes care of closing your database connections, you can explicitly close the
connection.

$db->close();

QUERIES IN CODEIGNITER

- To submit a query, use the query function:

$db = db_connect();
$db->query('PUT QUERY HERE');

RESULT ARRAYS
- Use the getResult() method to return the query result as an array of objects, or an empty array on failure.

$query = $db->query('YOUR QUERY');

foreach ($query->getResult() as $row) {


echo $row->title;
echo $row->name;
echo $row->body;
}

- Use the getResultArray() method to return the query result as a pure array, or an empty array when no result
is produced.
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

$query = $db->query('YOUR QUERY');

foreach ($query->getResultArray() as $row) {


echo $row['title'];
echo $row['name'];
echo $row['body'];
}

RESULT ROWS
- Use the getRow() method to return a single result row.
- If your query has more than one row, it returns only the first row. The result is returned as an object.

$query = $db->query('YOUR QUERY');

$row = $query->getRow();

if (isset($row)) {
echo $row->title;
echo $row->name;
echo $row->body;
}

CODEIGNITER MODELS

Notes in Designing CodeIgniter Models


Models as Tables
- The models in a CodeIgniter 4 application typically represent the database tables that store the application
data.
- So, the first step in deciding what models to create is to identify the database tables that are necessary for
storing the application data.

Separation of Concern
- CodeIgniter follows the Model-View-Controller (MVC) architectural pattern, which means that Models should
only be concerned with data storage and retrieval.
- It is important to keep this separation of concerns in mind when designing your Models, so that they don't
become bloated with unnecessary logic.

Model Naming
- CodeIgniter 4 Models should be named using a singular noun that represents the entity that they are
modeling.
- For example, if you have a database table named users, your Model should be named UserModel.
- This convention makes it easy to understand the purpose of each Model.
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

Model Methods
- Models should contain methods for performing CRUD (Create, Read, Update, Delete) operations on the data
they represent.
- These methods should be named in a way that makes it clear what they do.
- For example, a method for retrieving all users from the database might be named getAllUsers().

Validation
- It is important to validate data before inserting or updating it in the database.
- CodeIgniter 4 provides a robust validation library that can be used to ensure that data is valid before it's
saved to the database.

Creating and Configuring a Model


- To create a new model in CodeIgniter 4, you need to follow these steps:

1. Navigate to the app/Models folder within your CodeIgniter 4 project.


2. Create a new PHP file with the name of your model.
For example, if you want to create a model for a users table, you can create a file named UsersModel.php.
3. Inside the PHP file, create a new class with the same name as the file, extending the Model class from
CodeIgniter\Model package.
4. Add a use for the package CodeIgniter\Model before the class.
5. Define the database table that the model will be associated with using the $table property.
For example, if you want to associate the model with a users table, you can set the $table property to 'users'.
6. Define any other necessary properties, such as the primary key, etc using the $primaryKey, etc properties, as
needed.
7. Define any custom methods or properties that you need for your model.
8. Make sure you already configured the Database.php file located in app/Config folder.

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model


{
protected $table = 'users';
protected $primaryKey = 'id';
protected $useTimestamps = true;

// Add any custom methods or properties here


}
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

- The model class has some configuration options that can be set to allow the class’ methods to work
seamlessly for you. The most common are the following.

$table
- This variable defines the name of the database table associated with the Model.
- By default, CodeIgniter 4 assumes that the table name is the same as the Model name in plural form.
- For example, if you have a PostModel, the associated table name would be posts.
- However, you can override this default behavior by setting the $table variable explicitly.

$primaryKey
- This variable defines the name of the primary key column for the Model's associated table.
- By default, CodeIgniter 4 assumes that the primary key column name is id.
- However, you can override this default behavior by setting the $primaryKey variable explicitly.

$allowedFields
- This variable defines the list of columns that are allowed to be inserted or updated in the database table
associated with the Model.
- By default, CodeIgniter 4 allows all columns to be inserted or updated.
- However, you can override this default behavior by setting the $allowedFields variable explicitly.

$useTimestamps
- This variable defines whether the Model should automatically update the created_at and updated_at
columns in the database table associated with the Model.
- By default, CodeIgniter 4 assumes that the database table has created_at and updated_at columns, and sets
$useTimestamps to true.
- However, you can override this default behavior by setting the $useTimestamps variable explicitly.

Accessing a Model
- In CodeIgniter 4, you can access models in your controllers or other classes using the model() method or
creating a new instance of the Model class.

- For example, if you have a PostModel, you can create a new instance of it in your Controller like this:

namespace App\Controllers;

use App\Models\UserModel;

class Posts extends BaseController


{
public function index()
{
$userModel = new UserModel();
// Use the $model object to access the Model's methods
}
}
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

CODEIGNITER CRUD OPERATIONS

- In CodeIgniter 4 Models Several functions are provided for doing basic CRUD work on your tables, including
find(), insert(), update(), delete() and more.

1. Creating Records
- To create a new record in the database, you need to use the insert() method provided by the CodeIgniter
Model.
- This method takes an associative array of key-value pairs representing the column names and their
corresponding values for the record to be inserted.

$arrayName = [
'key1' => 'value1',
'key2' => 'value2',
'keyN' => 'valueN'
];

- The array’s keys must match the name of the columns in the $table, while the array’s values are the values to
save for that key.

For example:
$data = [
'username' => 'patty',
'email' => '[email protected]',
];

// Inserts data and returns inserted row's primary key


$userModel ->insert($data);

// Inserts data and returns true on success and false on failure


$userModel->insert($data, false);

// Returns inserted row's primary key


$userModel->getInsertID();

2. Reading Records
- To retrieve records from the database, you can use the find() method to retrieve a single record based on its
primary key or the findAll() method to retrieve all records from the table.
- If no parameters are passed in, find() will return all rows in that model’s table, effectively acting like findAll(),
though less explicit.
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

For example:
// Retrieve a single record by primary key
$user = $userModel->find(1);

// Retrieve all records


$users = $userModel->findAll();

where() method
- In CodeIgniter 4, you can retrieve records from a database table with specific criteria using the where()
method of the model class.
- The where() method allows you to specify conditions that the retrieved records must meet.

// Retrieve records with specific criteria


$users = $userModel->where('author', 'John Doe')->findAll();

3. Updating Records
- To update an existing record, you can use the update() method provided by the CodeIgniter 4 Model.
- This method takes an associative array of key-value pairs representing the column names and their
corresponding values to be updated for the record.
- The first parameter is the $primaryKey of the record to update.
- The array’s keys must match the name of the columns in a $table, while the array’s values are the values to
save for that key.

For example:
$data = [
'username' => 'patty',
'email' => '[email protected]',
];

$userModel->update($id, $data);

4. Deleting Records
- To delete an existing record, you can use the delete() method provided by the CodeIgniter 4 Model.
- Takes a primary key value as the first parameter and deletes the matching record from the model’s table.

For example:
// Deletes the matching record of the primary key
$userModel->delete(12);

- If no parameters are passed in, it will require a where method call:


// Deletes the matching record of the primary key
$userModel->where('id', 12)->delete();
TECHNOLOGICAL UNIVERSITY OF THE PHILIPPINES
TAGUIG CAMPUS CodeIgniter Models
Bachelor of Technical Vocational Teacher Education
Basic Arts and Sciences Department
ITEL131-T: IT Elective 2 CHAPTER 8

CODEIGNITER DATA VALIDATION

- Data validation is the process of ensuring that data entered by users is correct, complete, and valid.
- The Model class provides a way to automatically have all data validated prior to saving to the database with
the insert(), update(), or save() methods.
- When you update data, by default, the validation in the model class only validates provided fields. This is to
avoid validation errors when updating only some fields.

- The first step is to fill out the $validationRules property with the fields and rules that should be applied.
- If you have custom error message that you want to use, place them in the $validationMessages array:
<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model


{
protected $validationRules = [
'username' => 'required|alpha_numeric_space|min_length[3]',
'email' => 'required|valid_email|is_unique[users.email]',
'password' => 'required|min_length[8]',
'pass_confirm' => 'required_with[password]|matches[password]',
];
protected $validationMessages = [
'email' => [
'is_unique' => 'Sorry. That email has already been taken. Please choose
another.',
],
];
}

- The validation library provides several built-in rules that can be used to validate form data. Some of the
commonly used validation rules are:
1. required: Validates that a field is not empty.
2. matches: Validates that a field matches another field.
3. min_length: Validates that a field contains at least a minimum number of characters.
4. max_length: Validates that a field does not exceed a maximum number of characters.
5. exact_length: Validates that a field contains an exact number of characters.
6. valid_email: Validates that a field contains a valid email address.
7. valid_url: Validates that a field contains a valid URL.
8. numeric: Validates that a field contains only numeric characters.
9. alpha: Validates that a field contains only alphabetic characters.
10. alpha_numeric: Validates that a field contains only alpha-numeric characters.
11. alpha_dash: Validates that a field contains only alpha-numeric characters, underscores, and dashes.
12. is_unique: Validates that a field value is unique in a given database table and column.

- Multiple validation rules can be applied to a single field by separating them with the pipe (|) character.

You might also like