Introduction

Dalira is a lightweight PHP framework designed for developers seeking an elegant syntax and rapid runtime performance for development tasks. It promotes a clean separation of concerns, enhancing the organization and maintainability of web applications.

The framework handles data logic and database interactions, ensuring a clear structure for data management. It also manages the presentation layer, allowing developers to create dynamic and user-friendly interfaces without cluttering business logic. This simplicity and efficiency make Dalira an ideal choice for building robust web applications.

Getting Started

To begin using Dalira, download the framework here. Familiarize yourself with its file structure and core components to leverage its capabilities effectively. First, there is a requirement you should meet:

File Structure

The directory is organized to facilitate efficient development and maintainability.

   dalira-template/
   ├── app/                ← Application directory
   │   ├── layout/         ← Directory for headers and footers
   │   └── models/         ← Directory for CRUD operations
   ├── config/             ← Configuration directory
   └── public/             ← Public directory
     ├── css/              ← Directory for CSS files
     ├── img/              ← Directory for images
     └── js/               ← Directory for JS files
              

Starter Template

Create a new filename.php file in the root project. Include the header.php and footer.php files from a specified directory using their absolute paths. This method ensures that the files are included regardless of the current directory, allowing for consistent page structure.

filename.php

<?php include realpath(__DIR__ . '/app/layout/header.php') ?>

<h1>Hello world!</h1>

<?php include realpath(__DIR__ . '/app/layout/footer.php') ?>
                  

CSS & JS Components

Dalira utilizes Bootstrap 5.0.2 as its primary styling framework. This allows for a responsive and modern design, leveraging Bootstrap's grid system and components.

To modify the styling or update the Bootstrap version, you can make changes in the header.php and the footer.php file.

Steps to Change Bootstrap Version or Customize Styles

1. Locate header.php

  • Look for the link to the Bootstrap CSS file, which typically appears as shown in the code below. You can either change or update it, or replace it with another CSS framework.
app/layout/header.php

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
                  

2. Locate footer.php

  • Locate the Bootstrap-related script, typically formatted as shown in the code below. This script is essential for Bootstrap's JavaScript functionality, and you can update it or replace it with another framework as needed.
app/layout/footer.php

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
                  

Integrations

Integration simplifies the development process by enabling developers to effortlessly connect various components and services within their applications. This functionality enhances capabilities, facilitates seamless data exchanges, and improves overall performance, allowing developers to focus on creating elegant and high-performing web applications. By leveraging these integration capabilities, teams can ensure their applications are well-structured and capable of adapting to evolving requirements while scaling effectively.

Database

Setting up the database is simple just download the example database from here and import it on your phpmyadmin. After that, you'll need to update the connector.php file located in config/database. Change the private variable db to your desired database name.

The PHP code defines a class DBConnection with private properties for the database host, user, password, and database name, and includes a protected connect method that constructs a Data Source Name (DSN) to establish a connection using PDO. It handles exceptions by catching PDOException errors and printing them if they occur.

config/db/conn.php

<?php

class DBConnection
{
  private $host = "localhost";
  private $user = "root";
  private $pass = "";
  private $db = "dalira";

  protected function connect()
  {
    try {
      $dsn = 'mysql:host=' > . $this->host . ';dbname=' > . $this->db;
      $pdo = new PDO($dsn, $this->user, $this->pass);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      return $pdo;
    } catch (PDOException $e) {
      print_r($e);
    }
  }
}

?> 
                

Utilities

Utilities are vital for improving development efficiency and addressing common tasks. These tools facilitate data handling, validation, and formatting, empowering developers to create robust applications without unnecessary complexity. By utilizing these utilities, developers can produce cleaner code and optimize performance, thus speeding up the development cycle and ensuring a higher quality outcome in their web projects.

Models

Models are frequently utilized to streamline the handling of database interactions, covering a wide range of tasks including data retrieval, insertion, updating, and deletion. Typically, these models are structured within the specified directory arrangement. Below, you'll find a demonstrative example illustrating the creation of a model designed specifically to execute CRUD (Create, Read, Update, Delete) operations.

app/models

<?php

class ModelsFacade extends DBConnection
{

  function create($data)
  {
    $sql = $this->connect()->prepare("INSERT INTO dalira_table (data) VALUES (?)");
    $sql->execute([$data]);
    return $sql;
  }

  function read()
  {
    $sql = $this->connect()->prepare("SELECT * FROM dalira_table");
    $sql->execute();
    return $sql;
  }

  function update($data, $dataId)
  {
    $sql = $this->connect()->prepare("UPDATE dalira_table SET data = '$data' WHERE id = '$dataId'");
    $sql->execute();
    return $sql;
  }

  function delete($dataId)
  {
    $sql = $this->connect()->prepare("DELETE FROM dalira_table WHERE id = ?");
    $sql->execute([$dataId]);
    return $sql;
  }

}

?>
                
Initializing Models

Once a model is created, it needs to be initialized before it can be utilized on any page. To initialize the model, it should be included in the header file as demonstrated in the code.

app/layout/header.php

// Include necessary files for database connectivity and facade classes
include(__DIR__ . '/../../config/db/connector.php');

include(__DIR__ . '/../../app/models/models-facade.php');

$modelsFacade = new ModelsFacade;
                

CRUD

CRUD (Create, Read, Update, Delete) operations form the backbone of data management in web applications, enabling developers to efficiently handle data lifecycles.

  • Create use for the addition of new records.
  • Read use for the retrieval of created records.
  • Update use for the modification of existing records.
  • Delete use for the removal of existing records.

This comprehensive approach not only streamlines data handling but also enhances application performance.

Create

<?php 

include realpath(__DIR__ . '/app/layout/header.php');

// Check if the form has been submitted
if (isset($_POST['submit'])) {
  // Retrieve the submitted data from the form
  $data = $_POST['data'];

  // Validate that the data is not empty
  if (empty($data)) {
    // If the data is empty, add an error message to the $invalid array
    array_push($invalid, "Data should not be empty.");
  } 
  
  // If no validation errors have been encountered
  if (count($invalid) == 0) {
    // Attempt to create a new entry with the provided data
    $create = $modelsFacade->create($data);
    
    // Check if the creation was successful
    if ($create) {
      // If successful, add a success message to the $success array
      array_push($success, "Data has been inserted successfully.");
    }
  }
}

?>

<?php include realpath(__DIR__ . '/errors.php') ?>
<form action="test.php" method="post">
    <input type="text" placeholder="Data" name="data">
    <button type="submit" name="submit">Submit</button>
</form>

<?php include realpath(__DIR__ . '/app/layout/footer.php') ?>                  
                
Read

<?php include realpath(__DIR__ . '/app/layout/header.php') ?>

<table>
    <thead>
        <tr>
            <th>Data</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        // Fetch the data from the database using the read method
        $read = $modelsFacade->read();
        
        // Loop through each record returned from the database
        foreach ($read as $data) { ?>
            <tr>
                <td><?= htmlspecialchars($data['data']) ?></td>
                <td>
                    <a href="update.php?id=<?= htmlspecialchars($data['id']) ?>">Update</a>
                    <a href="delete.php?id=<?= htmlspecialchars($data['id']) ?>">Delete</a>
                </td>
            </tr>
        <?php } ?>
    </tbody>
</table>

<?php include realpath(__DIR__ . '/app/layout/footer.php') ?>