bg_image
header

Storyblok

Storyblok is a user-friendly, headless Content Management System (CMS) that helps developers and marketing teams create, manage, and publish content quickly and efficiently. It offers a visual editing interface for real-time content design and is flexible with various frameworks and platforms. Its API-first architecture allows content to be delivered to any digital platform, making it ideal for modern web and app development.


Prepared Statements

A Prepared Statement is a programming technique, especially used when working with databases, to make SQL queries more secure and efficient.

1. How does a Prepared Statement work?

It consists of two steps:

  1. Prepare the SQL query with placeholders
    Example in SQL:

SELECT * FROM users WHERE username = ? AND password = ?

 

 

  • (Some languages use :username or other types of placeholders.)

  • Bind parameters and execute
    The real values are bound later, for example:

 

$stmt->bind_param("ss", $username, $password);
$stmt->execute();

2. Advantages

Protection against SQL injection:
User input is treated separately and safely, not directly inserted into the SQL string.

Faster with repeated use:
The SQL query is parsed once by the database server and can be executed multiple times efficiently (e.g., in loops).


3. Example in PHP using MySQLi

$conn = new mysqli("localhost", "user", "pass", "database");
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email); // "s" stands for string
$email = "example@example.com";
$stmt->execute();
$result = $stmt->get_result();

In short:

A Prepared Statement separates SQL logic from user input, making it a secure (SQL Injection) and recommended practice when dealing with databases.


Outer Join

An Outer Join is a type of database join (commonly used in SQL) that returns records from one or both tables even if there’s no matching record in the other table.

Types of Outer Joins:

  1. LEFT OUTER JOIN (or simply: LEFT JOIN):
    → Returns all records from the left table, and the matching ones from the right table.
    → If there’s no match, the result is filled with NULL values from the right table.

  2. RIGHT OUTER JOIN (or: RIGHT JOIN):
    → Returns all records from the right table, and the matching ones from the left table.
    → If there’s no match, NULL is used for the left side.

  3. FULL OUTER JOIN:
    → Returns all records from both tables, with NULL where no match exists on either side.


Example:

Suppose you have two tables:

  • Customers

    CustomerID Name
    1 Anna
    2 Bernd
    3 Clara
  • Orders

    OrderID CustomerID Product
    101 2 Book
    102 4 Lamp

LEFT JOIN (Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID)

CustomerID Name OrderID Product
1 Anna NULL NULL
2 Bernd 101 Book
3 Clara NULL NULL

Transaction Control Language - TCL

Transaction Control Language (TCL) is a subset of SQL used to manage transactions in a database. A transaction is a logical unit of work that may consist of one or more SQL statements—typically INSERT, UPDATE, or DELETE—that should be executed together.

TCL provides commands to ensure that transactions are properly completed or rolled back in case of errors.

Main TCL Commands:

Command Description
COMMIT Saves all changes made in the current transaction permanently to the database.
ROLLBACK Undoes all changes made since the last COMMIT.
SAVEPOINT Creates a named point within a transaction that you can roll back to later.
ROLLBACK TO SAVEPOINT Reverts changes back to a specific savepoint.
SET TRANSACTION Defines characteristics for the current transaction (e.g., isolation level).
BEGIN;

UPDATE account SET balance = balance - 100 WHERE account_id = 1;
UPDATE account SET balance = balance + 100 WHERE account_id = 2;

COMMIT;

→ Both updates are completed together. If an error occurs, you could use ROLLBACK to cancel both operations.

Note:

TCL commands only work in database systems that support transactions (e.g., PostgreSQL, Oracle, or MySQL with InnoDB).


Data Manipulation Language - DML

ChatGPT:

Data Manipulation Language (DML) is a subset of SQL (Structured Query Language) used to manage and manipulate data within a database. With DML, users can insert, query, update, and delete data — essentially everything you'd typically do with data stored in a database.

The main DML commands are:

Command Purpose
SELECT Retrieve data from a table
INSERT Add new data
UPDATE Modify existing data
DELETE Remove data
-- Insert
INSERT INTO customers (name, city) VALUES ('Müller', 'Berlin');

-- Query
SELECT * FROM customers WHERE city = 'Berlin';

-- Update
UPDATE customers SET city = 'Hamburg' WHERE name = 'Müller';

-- Delete
DELETE FROM customers WHERE name = 'Müller';

Key Points:

  • DML deals with the data inside tables, not with the structure of the tables themselves (that's handled by Data Definition Language, DDL).

  • DML operations can often be rolled back (undone), especially when transactions are supported.

In short: DML is the toolset you use to keep your database dynamic and interactive by constantly adding, reading, modifying, or deleting data.


Entity Manager

💡 What is an Entity Manager?

An Entity Manager is a core component of ORM (Object-Relational Mapping) frameworks, especially in Java (JPA – Java Persistence API), but also in other languages like PHP (Doctrine ORM).


📦 Responsibilities of an Entity Manager:

  1. Persisting:

  2. Finding/Loading:

    • Retrieves an object by its ID or other criteria.

    • Example: $entityManager->find(User::class, 1);

  3. Updating:

    • Tracks changes to objects and writes them to the database (usually via flush()).

  4. Removing:

    • Deletes an object from the database.

    • Example: $entityManager->remove($user);

  5. Managing Transactions:

    • Begins, commits, or rolls back transactions.

  6. Handling Queries:


🔁 Entity Lifecycle:

The Entity Manager tracks the state of entities:

  • managed (being tracked),

  • detached (no longer tracked),

  • removed (marked for deletion),

  • new (not yet persisted).


🛠 Example with Doctrine (PHP):

$user = new User();
$user->setName('Max Mustermann');

$entityManager->persist($user); // Mark for saving
$entityManager->flush();        // Write to DB

✅ Summary:

The Entity Manager is the central component for working with database objects — creating, reading, updating, deleting. It abstracts SQL and provides a clean, object-oriented way to interact with your data layer.


Doctrine Database Abstraction Layer - DBAL

Doctrine DBAL (Database Abstraction Layer) is a PHP library that provides an abstraction layer for database access. It is part of the Doctrine project (a popular ORM for PHP), but it can be used independently of the ORM.


Purpose and Benefits of Doctrine DBAL:

Doctrine DBAL offers a unified API to interact with different databases (such as MySQL, PostgreSQL, SQLite, etc.) without writing raw SQL specific to each database system.


Key Features of Doctrine DBAL:

  • Connection Management
    • Easily configure and manage connections to various database systems.

    • Supports connection pooling, transactions, and more.

  • SQL Query Builder
    • Build SQL queries programmatically using an object-oriented API:

$qb = $conn->createQueryBuilder();
$qb->select('u.id', 'u.name')
   ->from('users', 'u')
   ->where('u.age > :age')
   ->setParameter('age', 18);
$stmt = $qb->executeQuery();
  • Database Independence

    • The same code works with different database systems (e.g., MySQL, PostgreSQL) with minimal changes.

  • Schema Management

    • Tools to create, update, and compare database schemas.

    • Useful for migrations and automation.

  • Data Type Conversion

    • Automatically converts data between PHP types and database-native types.

 

use Doctrine\DBAL\DriverManager;

$conn = DriverManager::getConnection([
    'dbname' => 'test',
    'user' => 'root',
    'password' => '',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
]);

$result = $conn->fetchAllAssociative('SELECT * FROM users');

When to Use DBAL Instead of ORM:

You might choose DBAL without ORM if:

  • You want full control over your SQL.

  • Your project doesn't need complex object-relational mapping.

  • You're working with a legacy database or custom queries.


Summary:

Doctrine DBAL is a powerful tool for clean, portable, and secure database access in PHP. It sits between raw PDO usage and a full-featured ORM like Doctrine ORM, making it ideal for developers who want abstraction and flexibility without the overhead of ORM logic.

 


Join Point

A Join Point is a concept from Aspect-Oriented Programming (AOP).

Definition:

A Join Point is a specific point during the execution of program code where additional behavior (called an aspect) can be inserted.

Typical examples of Join Points:

  • Method calls

  • Method executions

  • Field access (read/write)

  • Exception handling

Context:

In AOP, cross-cutting concerns (like logging, security, or transaction management) are separated from the main business logic. These concerns are applied at defined points in the program flow — the Join Points.

Related terms:

  • Pointcut: A way to specify which Join Points should be affected (e.g., "all methods starting with save").

  • Advice: The actual code that runs at a Join Point (e.g., "log this method call").

  • Aspect: A combination of Pointcut(s) and Advice(s) — the full module that implements a cross-cutting concern.

Example (in Spring AOP):

@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethod(JoinPoint joinPoint) {
    System.out.println("Calling method: " + joinPoint.getSignature().getName());
}

→ This logs a message before every method call in a specific package. The joinPoint.getSignature() call provides details about the actual Join Point.


Aspect Oriented Programming - AOP

Aspect-Oriented Programming (AOP) is a programming paradigm focused on modularizing cross-cutting concerns—aspects of a program that affect multiple parts of the codebase and don't fit neatly into object-oriented or functional structures.


💡 Goal:

Typical cross-cutting concerns include logging, security checks, error handling, transaction management, or performance monitoring. These concerns often appear in many classes and methods. AOP allows you to write such logic once and have it automatically applied where needed.


🔧 Key Concepts:

  • Aspect: A module that encapsulates a cross-cutting concern.

  • Advice: The actual code to be executed (e.g., before, after, or around a method call).

  • Join Point: A point in the program flow where an aspect can be applied (e.g., method execution).

  • Pointcut: A rule that defines which join points are affected (e.g., "all methods in class X").

  • Weaving: The process of combining aspects with the main program code—at compile-time, load-time, or runtime.


🛠 Example (Java with Spring AOP):

@Aspect
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBeforeMethod(JoinPoint joinPoint) {
        System.out.println("Calling method: " + joinPoint.getSignature().getName());
    }
}

This code automatically logs a message before any method in the com.example.service package is executed.


✅ Benefits:

  • Improved modularity

  • Reduced code duplication

  • Clear separation of business logic and system-level concerns


❌ Drawbacks:

  • Can reduce readability (the flow isn't always obvious)

  • Debugging can become more complex

  • Often depends on specific frameworks (e.g., Spring, AspectJ)


Design by Contract - DbC

Design by Contract (DbC) is a concept in software development introduced by Bertrand Meyer. It describes a method to ensure the correctness and reliability of software by defining clear "contracts" between different components (e.g., methods, classes).

Core Principles of Design by Contract

In DbC, every software component is treated as a contract party with certain obligations and guarantees:

  1. Preconditions
    Conditions that must be true before a method or function can execute correctly.
    → Responsibility of the caller.

  2. Postconditions
    Conditions that must be true after the execution of a method or function.
    → Responsibility of the method/function.

  3. Invariant (Class Invariant)
    Conditions that must always remain true throughout the lifetime of an object.
    → Responsibility of both the method and the caller.

Goal of Design by Contract

  • Clear specification of responsibilities.

  • More robust and testable software.

  • Errors are detected early (e.g., through contract violations).

Example in Pseudocode

class BankAccount {
    private double balance;

    // Invariant: balance >= 0

    void withdraw(double amount) {
        // Precondition: amount > 0 && amount <= balance
        if (amount <= 0 || amount > balance) throw new IllegalArgumentException();

        balance -= amount;

        // Postcondition: balance has been reduced by amount
    }
}

Benefits

  • Clear contracts reduce misunderstandings.

  • Easier debugging, as violations are detected immediately.

  • Supports defensive programming.

Drawbacks


Random Tech

Doctrine Database Abstraction Layer - DBAL


doctrine-logo-6B6BF1A613-seeklogo.com.png