PHPackages                             lanous/db - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. lanous/db

ActiveLibrary[Database &amp; ORM](/categories/database)

lanous/db
=========

v1.0-beta.2(2y ago)00MITPHPPHP &gt;=8.3.0

Since Apr 6Pushed 2y ago1 watchersCompare

[ Source](https://github.com/lanous/db)[ Packagist](https://packagist.org/packages/lanous/db)[ RSS](/packages/lanous-db/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)DependenciesVersions (4)Used By (0)

Introduction
============

[](#introduction)

The primary objective of this project is to seamlessly interact with various database systems without the need for in-depth knowledge of their intricate structures and complex commands. Its inherent flexibility empowers developers, and its potential for further enhancement is substantial. These accompanying documents cater specifically to users of this project, while development-related documentation resides within the `src` directory.

Navigating Complexity
=====================

[](#navigating-complexity)

At first glance, the project’s initial complexity might deter some, leading them to question its suitability for open-source endeavors. However, let us delve into the reasons why this library can be an invaluable asset, especially for personal projects:

**Automatic Data Encryption**: The project handles data encryption seamlessly, ensuring that sensitive information remains secure.

**Extensible Data Type Structures**: The data type structures are designed to be extensible, accommodating diverse use cases.

**Abstraction from Database Complexity**: By shielding developers from the intricacies of database management, this project simplifies interactions.

**Scalability**: The architecture is inherently scalable, allowing seamless growth as your project evolves.

In summary, while the initial learning curve may be challenging, the rewards of using this project far outweigh the effort invested. Whether you’re embarking on a personal project or contributing to open-source initiatives, consider leveraging this powerful tool to streamline your database interactions.

Overview
========

[](#overview)

```
$database = new Database\Connect(new LanousConfig);

$Table = $database->OpenTable (MyLanous\Table\Users::class);

$Where = $Table->Where(MyLanous\Table\Users::ID,"=",1);

$data = $Table->Select(
    column: "*",
    distinct: true
)->Extract();

$data->LastRow($data::ObjectType)->first_name->value;
```

The elegance of this project lies in its adherence to object-oriented principles. As you’ve astutely observed, everything is meticulously organized within class structures. Specifically, your data tables should be encapsulated within well-defined class hierarchies, following established rules and principles. Let’s delve into the key aspects:

1. **Class-Based Data Tables**: Each data table corresponds to a class. This encapsulation ensures that data remains neatly compartmentalized, enhancing readability and maintainability.
2. **Principled Design**: Define your classes with care. Consider the relationships between tables, inheritance hierarchies, and the appropriate access modifiers. A thoughtful design ensures efficient data manipulation.
3. **Effective Data Handling**: By leveraging class methods, you can perform data operations seamlessly. Whether it’s querying, updating, or inserting records, encapsulating these actions within class methods promotes consistency and reduces redundancy.
4. **Abstraction and Encapsulation**: Hide implementation details behind well-defined interfaces. This abstraction shields the rest of your project from the intricacies of data handling, promoting modularity.
5. **Data Integrity and Validation**: Implement validation checks within your class methods. Ensure that data adheres to predefined rules before it enters the database. This prevents erroneous entries and maintains data integrity.

Example of defined table
------------------------

[](#example-of-defined-table)

```
        $this->AddColumn("ID")
            ->DataType(\MyLanous\DataTypes\Integer::class)
            ->Size(255)
            ->AutoIncrement(true)
            ->Constraints(Primary: true);

        $this->AddColumn("first_name")
            ->DataType(\MyLanous\DataTypes\Varchar::class)
            ->Size(255);

        $this->AddColumn("last_name")
            ->DataType(\MyLanous\DataTypes\Varchar::class)
            ->Size(255);

        $this->AddColumn("password")
            ->DataType(\MyLanous\DataTypes\Varchar::class)
            ->Size(255);

        $this->AddColumn("address")
            ->DataType(\MyLanous\DataTypes\ArrayData::class);

        # ---------- Data Handling
        $this->Injection("first_name")
            ->Edit(fn($data) => strtolower($data));
        $this->Injection("last_name")
            ->Edit(fn($data) => strtolower($data));

        # Base64 encode/decode password
        $this->Injection("password")
            ->Edit(fn($data) => base64_encode($data));
        $this->Extract("password")
            ->Edit(fn($data) => base64_decode($data));
```

As you can see, data types are of class type and we have placed an example of this class below.

```
class ArrayData implements \Lanous\db\Structure\DataType {
    const Query = "JSON";
    # The data being input and output is passed to the construct.
    private $data;
    public function __construct($data) {
        $this->data = $data;
    }
    # Before data is entered into the database, it passes through this function.
    public function Injection($data) {
        return json_encode($data);
    }
    # After data is extracted from the database, it also passes through this function.
    public function Extraction($data) {
        return json_decode($data,1);
    }
    # By using this function, we prevent specific types or expressions from entering the database.
    public function Validation($data): bool {
        return is_array($data);
    }
    # You can also add specific functions to these data types.
    # Stay tuned for more documentation!
}
```

Idioms
======

[](#idioms)

General
-------

[](#general)

### Database

[](#database)

A database serves as a structured repository for a collection of data. It provides accessibility and editability, acting as a vital foundation for various applications and systems.

### Database Management System (DBSM)

[](#database-management-system-dbsm)

A Database Management System (DBMS) is sophisticated software equipped with a suite of tools for efficiently handling database data. It serves as the bridge between applications and the underlying database, facilitating seamless communication and interaction.

### Tables: Organized Data Repositories

[](#tables-organized-data-repositories)

Data within a database is systematically organized into tables. Each table represents a distinct category of related information. For instance, consider the “user information” table, which houses essential identity details such as names, surnames, and birthdates. This structured approach ensures that data finds its rightful place within the system.

### Columns: The Essence of Data

[](#columns-the-essence-of-data)

Columns lie at the heart of data representation. They define the nature of the information stored. Within a table, columns hold specific data points. For example, the “last name” column neatly captures users’ surnames. Each column boasts unique attributes, including data type, size, constraints, and other relevant properties.

##### A. Primary Columns: Uniqueness and Identification

[](#a-primary-columns-uniqueness-and-identification)

When a column assumes the role of a primary key, it becomes a distinctive identifier—a digital fingerprint—for individual data rows. By enforcing uniqueness, it prevents duplicate values within that column. Typically, the primary key column bears the name “id.” Throughout the program, this ID serves as the universal means of identifying users.

##### B. Foreign Key Columns: Building Relationships

[](#b-foreign-key-columns-building-relationships)

A foreign key establishes a crucial relationship between tables. By referencing the primary key of another table, it ensures data consistency. This linkage allows data to flow seamlessly across related tables, fostering integrity and coherence.

Setting Up the Lanous\\db Package: A Step-by-Step Guide
=======================================================

[](#setting-up-the-lanousdb-package-a-step-by-step-guide)

1. Installation via Composer
----------------------------

[](#1-installation-via-composer)

Begin by installing the Lanous\\db package using Composer.

```
composer require lanous\db
```

2. Autoloading
--------------

[](#2-autoloading)

Once the installation is complete, it’s time to seamlessly integrate the package into your project.

in your main project file (often named `index.php`), include the Composer-generated autoload.php. This file acts as the gateway, ensuring that all necessary classes and dependencies are loaded:

```

```

Embrace the Power of Lanous\\db
-------------------------------

[](#embrace-the-power-of-lanousdb)

With the package seamlessly integrated, you’re now equipped to harness the capabilities of Lanous\\db. Whether you’re querying, updating, or managing data, let this elegant solution simplify your database interactions.

Remember, elegance lies not only in functionality but also in the meticulous steps taken to achieve it. Happy coding!

Setting Up Database Connectivity: A Pragmatic Approach
------------------------------------------------------

[](#setting-up-database-connectivity-a-pragmatic-approach)

Once your project is successfully loaded, the next crucial step is establishing a seamless connection to the database. This pivotal task is accomplished through the Connect class within your project. However, before diving into the connection process, let’s lay the groundwork by creating a robust configuration class

The Config Class: Constants for Clarity
---------------------------------------

[](#the-config-class-constants-for-clarity)

Your Config class serves as the cornerstone of your database setup.

It encapsulates essential constants that dictate how your project interacts with the database. These constants include:

`hostname`: The database server’s address (e.g., '127.0.0.1').

`username`: The authorized database user (e.g., 'root').

`password`: The secret key granting access.

`database`: The specific database name to connect to (e.g., 'lanous').

`dbsm`: The Database Management System (DBMS) in use (e.g., 'mysql').

`project_name`: A descriptive identifier for your project (e.g., 'MyLanous').

`project_dir`: The absolute path to your project directory (automatically determined).

Here’s an illustrative example of a well-structured LanousConfig class:

```
class LanousConfig {
    const hostname = '127.0.0.1';
    const username = 'root';
    const password = '';
    const database = 'lanous';
    const dbsm = 'mysql';
    const project_name = 'MyLanous';
    const project_dir = __DIR__;
}
```

### Leveraging Library Constants: Clarity and Safety

[](#leveraging-library-constants-clarity-and-safety)

To configure the DBMS effectively, utilize library constants. These constants not only prevent typographical errors but also serve as informative markers for supported DBMS options. Consider this approach:

```
    // ...
    const dbsm = Database\Lanous::DBSM_Mysql; // Choose the appropriate constant
    // ...
```

Initiating the Connection
-------------------------

[](#initiating-the-connection)

With your configuration class in place, it’s time to forge the connection:

```
$database = new Database\Connect(new LanousConfig);
```

And just like that, your project gains access to the database, ready to perform its data magic.

Final code
----------

[](#final-code)

```
