Friday, June 21, 2024
CodeIgniter
When we reach the point where WordPress can no longer be customized to meet our needs, we need a framework. This could be a CRUD for a database, an API, or something similar.
What is a framework?
A framework is software that addresses issues of code redundancy and security. It acts as an "abstract layer" above plain PHP. A framework provides us with a set of classes and wrapper functions that simplify and speed up project development.
Why CodeIgniter?
It's very simple to use for people new to PHP.
Before installation, you should take a look at:
https://www.codeigniter.com/user_guide/
Installation
Use "composer" to install project:
composer create-project codeigniter4/appstarter project-root
And the we run development server:
cd project-root
php spark serve
Server is at local port:
http://localhost:8080/
Env
The .env (environment variables) file is where we keep local settings. If we look at .gitignore, we see that the .env file is ignored, which means the data in the file will not be pushed to Git. In CodeIgniter, we enter database access information and similar data into the .env file.
Copy env to .env:
cp env ./.env
nano .env
To get debugbar to work:
CI_ENVIRONMENT = development
What is a Controller?
A controller acts like a "remote controller," something through which we manage the other parts of the framework. Commands are entered via URL strings or routes. For example, "http://localhost:8080/users" typically maps the "/users" part to a class "UsersController" and its "index" method. Similarly, "http://localhost:8080/users/add" calls the "UsersController::add()" method. In a controller, we usually call model classes (database) and external libraries, and return View HTML template scripts.
To create a controller, enter the command:
php spark make:controller Hello --suffix
“./app/Controllers/HelloController.php” is created with data inside:
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class HelloController extends BaseController
{
public function index()
{
return "Hello world!"; //ubaci ovaj dio
}
}
Route
The /app/Config/routes.php file contains the routes. Here, we specify that the /hello route will call the HelloController->index() method. So we add:
$routes->get('hello', 'HelloController::index');
Now if we go to url: “http://localhost:8080/hello”, we see “Hello world!”.
View
The view is responsible for what is displayed in the browser, meaning HTML. We transfer variables from the controller like this:
namespace App\Controllers;
use App\Controllers\BaseController;
class HelloController extends BaseController
{
public function index()
{
$data['helloText'] = 'Hello from controller!';
return view('hello', $data);
}
}
Everything we want to transfer, we put into the $data array and add it to the view() function. The first argument is the name of the file in the /Views directory, and the second is the array with the variables we want to pass to the view file.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello</title>
<meta name="description" content="">
<meta name="author" content="">
</head>
<body>
<?php echo $helloText ?>
</body>
</html>
Now we have in url “http://localhost:8080/hello”:
Middleware
Middleware is code that runs before or after the controller. In CodeIgniter, middleware is referred to as a filter. For example, we can check a security token. If the token is invalid, the request will not reach the controller.
Create file:
app/Filters/AuthFilter.php
With content:
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (!isset($request->headers()['Authorization']))
{
error_log('NO AUTH TOKEN!');
}
else
{
//...
}
return $request;
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return $request;
}
}
To enable the filter, we need to add it to: “app/Config/Filters.php” under “$aliases”:
public $aliases = [
//...
'myauth' => AuthFilter::class ,
];
Libraries
These are additional classes that we can share between controllers. For example, session library or if you want to use PDO instead of built-in model you can create 'app/Libraries/MyModel.php'. And insert:
<?php
namespace App\Libraries;
class Mymodel
{
public function hello()
{
//...
}
}
We add lib to controller with:
use App\Libraries\Mymodel;
Model
Model – means working with database classes.
Enter in phpMyAdmin (or through the terminal):
DROP DATABASE IF EXISTS ci_app;
CREATE DATABASE ci_app;
DROP USER IF EXISTS 'ci_app'@'localhost';
CREATE USER 'ci_app'@'localhost' IDENTIFIED BY 'ci_app';
GRANT ALL ON ci_app.* TO 'ci_app'@'localhost';
USE ci_app;
CREATE TABLE members (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(120) DEFAULT NULL,
email varchar(120) DEFAULT NULL,
mobile varchar(45) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In the .env file, we set the access data for the database:
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci_app
database.default.username = ci_app
database.default.password = ci_app
database.default.DBDriver = MySQLi
database.default.DBPrefix =
We create the model file with:
php spark make:model Members --suffix
So we open: "/app/Models/MembersModel.php".
namespace App\Models;
use CodeIgniter\Model;
class MembersModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'members';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ["name", "email", "mobile"]; // <- ubacivamo dozvoljene stupce
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
We add the route in “/app/Config/routes.php”.
$routes->get('test-db', 'HelloController::testModel');
And in "HelloController.php" we add the controller:
use App\Models\MembersModel;
//...
public function testModel()
{
$membersModel = new MembersModel();
//$membersModel->where('id', 12)->delete(); // delete
//$membersModel->update($id, $data); // update
//$user = $membersModel->find($user_id); // find
//$users = $membersModel->findAll(); // find all
$membersModel->insert([
"name" => "Damir Sijakovic",
"email" => "damir.sijakovic@gmail.com",
"mobile" => "645654656"
]);
}
Now when we go to "http://localhost:8080/test-db", the data will be entered into the database.
That's enough for a start. Be sure to check out the CI documentation and category here for more.