In MySQL, a window function is a powerful feature that allows you to perform calculations across a set of rows in a query result. It operates on a "window" of rows defined by a specific partition and an optional ordering within that partition. Window functions are commonly used to perform calculations such as running totals, ranking, and moving averages.

window functions mysql

 

Here's an overview of the main components and concepts related to window functions in MySQL:

Syntax: Window functions are typically used in the SELECT clause of a query and follow a specific syntax:

<function_name>(expression) OVER (window_specification)

Function_name: This represents the specific window function you want to use, such as SUM, AVG, ROW_NUMBER, RANK, etc. MySQL provides various window functions for different calculations.


Expression: It is the column or expression on which you want to perform the window function calculation. For example, if you want to calculate the average of a column, the expression would be the column name.


Window_specification: It defines the window or subset of rows on which the window function operates. It consists of two main parts: PARTITION BY and ORDER BY.

 

PARTITION BY: This clause divides the result set into partitions or groups based on one or more columns. The window function is applied separately to each partition. If you omit the PARTITION BY clause, the entire result set is treated as a single partition.


ORDER BY: This clause determines the order of rows within each partition. It specifies the column(s) by which the data should be sorted. The window function calculations are then performed based on this ordering.

 


Examples: Let's say we have a table named "sales" with columns like "region", "year", and "revenue". If we want to calculate the average revenue per region, while maintaining the original row order, we can use the AVG window function as follows:

SELECT region, year, revenue,
       AVG(revenue) OVER (PARTITION BY region ORDER BY year) AS avg_revenue
FROM sales;

This query calculates the average revenue for each region, ordering the data by year within each region partition.

In PHP, a closure is an anonymous function that can access variables outside of its own scope. It "closes" over those variables and retains their values even if they are no longer in scope. This allows closures to have a persistent state and provides a way to create more flexible and powerful functions.

php closures

 

Examples:

 

Multiple closures from one function:

//...

function createMultiplier($factor) {
    return function($number) use ($factor) {
        return $number * $factor;
    };
}

$double = createMultiplier(2);
echo $double(5);  // Output: 10

$triple = createMultiplier(3);
echo $triple(5);  // Output: 15

//...

In this example, the createMultiplier() function returns a closure that multiplies a given number by the specified factor. The closure "closes" over the $factor variable from the parent scope using the use keyword. This allows the closure to access and retain the value of $factor even after createMultiplier() has finished executing.

We can create multiple closures using the createMultiplier() function. Each closure will have its own persistent state based on the value of $factor provided during its creation.

In the code above, we create two closures: $double and $triple. The first closure, $double, multiplies a number by 2, and the second closure, $triple, multiplies a number by 3. When we invoke each closure with the number 5, we get the expected results of 10 and 15, respectively.

Arrow functions, also known as short closures, were introduced in PHP 7.4 as a more concise syntax for defining anonymous functions. They provide a shorthand way to create simple, one-line functions without the need for the function keyword or explicit return statements.

 

Example of an arrow function in PHP

$addition = fn($a, $b) => $a + $b;
echo $addition(2, 3);  // Output: 5

In this example, the arrow function fn($a, $b) => $a + $b takes two arguments $a and $b and returns their sum directly. The result is then echoed using the echo statement.

 

Arrow functions have the following characteristics:

- They are always anonymous: Arrow functions do not have a name and cannot be referenced or called by name. They are intended for use as short, inline functions.
- They use the fn keyword: Arrow functions are declared using the fn keyword, followed by a list of parameters in parentheses ($a, $b in the example above), an arrow (=>), and the expression or statement to be executed.
- They inherit variables from the parent scope: Arrow functions automatically capture variables from the surrounding scope, similar to regular closures. This means they have access to variables defined outside the function's body.
- They have implicit return: If the arrow function consists of a single expression, the result of that expression is automatically returned. There's no need to use the return keyword explicitly.

PHP 8 introduced a new feature called attributes, which provide a way to add metadata or annotations to PHP code. Attributes allow developers to attach additional information to classes, methods, properties, parameters, and other code elements. This metadata can be used by frameworks, libraries, or tools to implement various behaviors or to perform automatic code generation. If you have worked with Symfony Framework, you should be very familiar with these attributes that in Symfony are called Annotations.

 

php 8 attributes

 

Key points about PHP 8 attributes:

- Declaration Syntax: Attributes are defined using the #[<Attribute>] syntax, where <Attribute> represents the name of the attribute. They can be placed before classes, methods, properties, and function parameters.
- Multiple Attributes: Multiple attributes can be applied to the same element by separating them with a comma. For example, #[Attribute1, Attribute2].
- Attribute Classes: Attributes are implemented as classes in PHP. An attribute class can be any valid PHP class, typically suffixed with "Attribute" to indicate its purpose.
- Attribute Targets: Attributes can be applied to different targets within PHP code, such as classes, methods, properties, function parameters, etc. Each attribute class specifies the valid targets it can be applied to using the #[<Attribute>(<Target>)] syntax, where <Target> represents the target element (e.g., class, method, property, parameter).
- Metadata Usage: The metadata provided by attributes can be accessed at runtime using reflection. Reflection APIs allow you to inspect the attributes applied to classes, methods, and other code elements and retrieve their values.
- Compiler Directives: Attributes can also be used as compiler directives to affect the compilation process. For example, the #[Deprecated] attribute can be used to mark a class or method as deprecated, generating warnings or errors during compilation.
- Custom Attributes: PHP 8 allows developers to create custom attributes by defining their own attribute classes. Custom attributes can provide additional behavior or functionality based on the metadata they carry.


Attributes provide a flexible mechanism for extending the capabilities of PHP and enable better integration with frameworks, libraries, and development tools. They enhance code readability and allow for more expressive and self-documenting code by associating relevant metadata directly with the code elements.

 

Basic Attribute Usage

#[Attribute]
class MyAttribute {
    public $value;

    public function __construct($value) {
        $this->value = $value;
    }
}

#[MyAttribute('Hello, world!')]
class MyClass {
    #[MyAttribute(42)]
    public $myProperty;

    #[MyAttribute('This is a method')]
    public function myMethod() {
        // ...
    }
}

// Retrieving attributes using Reflection
$reflectionClass = new ReflectionClass(MyClass::class);
$classAttributes = $reflectionClass->getAttributes();
$classAttribute = $classAttributes[0]->newInstance();
echo $classAttribute->value; // Output: Hello, world!

$reflectionProperty = $reflectionClass->getProperty('myProperty');
$propertyAttributes = $reflectionProperty->getAttributes();
$propertyAttribute = $propertyAttributes[0]->newInstance();
echo $propertyAttribute->value; // Output: 42

$reflectionMethod = $reflectionClass->getMethod('myMethod');
$methodAttributes = $reflectionMethod->getAttributes();
$methodAttribute = $methodAttributes[0]->newInstance();
echo $methodAttribute->value; // Output: This is a method

In this example, a basic attribute is defined and applied to a class, property, and method. The attributes are then retrieved using Reflection and their values are accessed.