Funzioni Built-in
Libreria completa di funzioni helper per sviluppare rapidamente applicazioni Flux
Ecosistema ricco: Flux include centinaia di funzioni built-in organizzate
in categorie logiche. Tutte sono disponibili globalmente senza import.
Funzioni Stringa
Manipolazione e formattazione di stringhe:
# Manipolazione base
str_upper("hello") # "HELLO"
str_lower("WORLD") # "world"
str_title("mario rossi") # "Mario Rossi"
str_capitalize("hello") # "Hello"
# Pulizia e trimming
str_trim(" hello ") # "hello"
str_ltrim(" hello") # "hello"
str_rtrim("hello ") # "hello"
str_clean(" hello world ") # "hello world"
# Ricerca e sostituzione
str_contains("hello world", "world") # true
str_starts_with("hello", "hel") # true
str_ends_with("hello", "llo") # true
str_replace("hello world", "world", "flux") # "hello flux"
str_replace_all("a-b-c", "-", "_") # "a_b_c"
# Divisione e join
str_split("a,b,c", ",") # ["a", "b", "c"]
str_join(["a", "b", "c"], "-") # "a-b-c"
# Lunghezza e substrings
str_length("hello") # 5
str_substring("hello", 1, 3) # "el"
str_left("hello", 3) # "hel"
str_right("hello", 3) # "llo"
# Padding e allineamento
str_pad_left("5", 3, "0") # "005"
str_pad_right("hi", 5, ".") # "hi..."
str_pad_center("hi", 6, "-") # "--hi--"
# Encoding e escape
str_slug("Hello World!") # "hello-world"
str_escape_html("<script>") # "<script>"
str_unescape_html("&") # "&"
str_base64_encode("hello") # "aGVsbG8="
str_base64_decode("aGVsbG8=") # "hello"
str_url_encode("hello world") # "hello%20world"
str_url_decode("hello%20world") # "hello world"
# Validazione
str_is_email("test@test.com") # true
str_is_url("https://test.com") # true
str_is_numeric("123") # true
str_is_alpha("abc") # true
str_is_alphanumeric("abc123") # true
Funzioni Array
Operazioni su array e liste:
# Informazioni base
array_length([1, 2, 3]) # 3
array_is_empty([]) # true
array_count([1, 2, 1], 1) # 2
# Accesso elementi
array_first([1, 2, 3]) # 1
array_last([1, 2, 3]) # 3
array_get([1, 2, 3], 1) # 2
array_get([1, 2, 3], 5, "default") # "default"
# Ricerca
array_contains([1, 2, 3], 2) # true
array_index_of([1, 2, 3], 2) # 1
array_find([1, 2, 3], lambda x: x > 2) # 3
# Aggiunta e rimozione
array_push([1, 2], 3) # [1, 2, 3]
array_pop([1, 2, 3]) # [1, 2] (rimuove ultimo)
array_shift([1, 2, 3]) # [2, 3] (rimuove primo)
array_unshift([2, 3], 1) # [1, 2, 3] (aggiunge all'inizio)
# Slicing e combinazione
array_slice([1, 2, 3, 4], 1, 2) # [2, 3]
array_merge([1, 2], [3, 4]) # [1, 2, 3, 4]
array_concat([1], [2], [3]) # [1, 2, 3]
# Ordinamento e manipolazione
array_reverse([1, 2, 3]) # [3, 2, 1]
array_sort([3, 1, 2]) # [1, 2, 3]
array_sort_desc([1, 3, 2]) # [3, 2, 1]
array_shuffle([1, 2, 3, 4]) # [2, 4, 1, 3] (casuale)
array_unique([1, 2, 2, 3]) # [1, 2, 3]
# Funzioni di ordine superiore
array_map([1, 2, 3], lambda x: x * 2) # [2, 4, 6]
array_filter([1, 2, 3, 4], lambda x: x > 2) # [3, 4]
array_reduce([1, 2, 3], lambda a, b: a + b, 0) # 6
# Raggruppamento
array_group_by(users, "role") # {"admin": [...], "user": [...]}
array_chunk([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], [5]]
# Conversioni
array_to_string([1, 2, 3], ", ") # "1, 2, 3"
array_from_string("1,2,3", ",") # ["1", "2", "3"]
Funzioni Numeriche
Calcoli matematici e formattazione numeri:
# Operazioni base
math_abs(-5) # 5
math_ceil(4.3) # 5
math_floor(4.7) # 4
math_round(4.6) # 5
math_round(4.567, 2) # 4.57
# Potenze e radici
math_pow(2, 3) # 8
math_sqrt(16) # 4
math_exp(2) # 7.389...
math_log(10) # 2.302...
# Trigonometria
math_sin(math_pi() / 2) # 1
math_cos(0) # 1
math_tan(math_pi() / 4) # 1
# Costanti
math_pi() # 3.14159...
math_e() # 2.71828...
# Min/Max
math_min(1, 2, 3) # 1
math_max(1, 2, 3) # 3
math_clamp(5, 1, 3) # 3 (limita tra 1 e 3)
# Numeri casuali
random() # 0.0 - 1.0
random_int(1, 10) # 1 - 10
random_float(1.0, 5.0) # 1.0 - 5.0
# Formattazione
number_format(1234.56) # "1,234.56"
number_format(1234.56, 1) # "1,234.6"
number_format(1234.56, 0, ".", " ") # "1 235"
# Conversioni
to_int("123") # 123
to_float("123.45") # 123.45
is_numeric("123") # true
is_integer(123.0) # false
# Percentuali e proporzioni
percentage(25, 100) # 25
percentage_of(25, 100) # 0.25
ratio(3, 4) # 0.75
Funzioni Data e Ora
Gestione date, orari e timezone:
# Data/ora corrente
now() # DateTime corrente
today() # Data odierna (00:00:00)
time() # Timestamp Unix corrente
# Creazione date
date("2024-12-25") # Da stringa
date(2024, 12, 25) # Da componenti
datetime("2024-12-25 10:30:00")
timestamp_to_date(1703505600)
# Formattazione
date_format(now(), "d/m/Y") # "25/12/2024"
date_format(now(), "F j, Y") # "December 25, 2024"
date_format(now(), "H:i:s") # "15:30:45"
date_iso(now()) # "2024-12-25T15:30:45Z"
# Parsing
date_parse("25/12/2024", "d/m/Y")
date_parse_iso("2024-12-25T15:30:45Z")
# Operazioni
date_add(date("2024-12-25"), days=7) # +7 giorni
date_sub(date("2024-12-25"), months=1) # -1 mese
date_diff(date1, date2, "days") # Differenza in giorni
# Estrazione componenti
date_year(now()) # 2024
date_month(now()) # 12
date_day(now()) # 25
date_hour(now()) # 15
date_minute(now()) # 30
date_second(now()) # 45
date_weekday(now()) # 1-7 (lunedì=1)
date_week_of_year(now()) # Settimana dell'anno
# Timezone
date_timezone(now(), "Europe/Rome")
date_utc(now())
timezone_offset("Europe/Rome")
# Validazione
is_date("2024-12-25") # true
is_valid_date(2024, 2, 30) # false (30 feb non esiste)
is_leap_year(2024) # true
# Date relative
date_human(now() - 3600) # "1 ora fa"
date_relative(date("2024-12-25")) # "tra 5 giorni"
# Periodi
date_start_of_day(now()) # Inizio giornata
date_end_of_month(now()) # Fine mese
date_start_of_week(now()) # Inizio settimana
Funzioni Validazione
Validazione dati e input utente:
# Validazione generale
is_empty("") # true
is_null(None) # true
is_blank(" ") # true
is_set(variable) # true se definita
# Tipi di dato
is_string("hello") # true
is_integer(123) # true
is_float(123.45) # true
is_boolean(true) # true
is_array([1, 2, 3]) # true
is_object({}) # true
# Validazione email
validate_email("test@test.com") # true
is_valid_email("invalid") # false
email_domain("test@gmail.com") # "gmail.com"
# URL e domini
validate_url("https://test.com") # true
is_secure_url("https://test.com") # true
url_domain("https://test.com/path") # "test.com"
# Numeri
validate_range(5, 1, 10) # true
is_positive(5) # true
is_negative(-5) # true
is_even(4) # true
is_odd(3) # true
# Password e sicurezza
validate_password_strength("MyPass123!") # {"score": 4, "feedback": [...]}
contains_uppercase("Hello") # true
contains_lowercase("Hello") # true
contains_numbers("Hello123") # true
contains_symbols("Hello!") # true
# Lunghezze
validate_length("hello", 3, 10) # true
min_length("hello", 3) # true
max_length("hello", 10) # true
# Pattern e regex
validate_pattern("123", r"\d+") # true
is_alpha_only("abc") # true
is_alphanumeric_only("abc123") # true
# Date
validate_date("2024-12-25") # true
is_future_date("2025-01-01") # true
is_past_date("2023-01-01") # true
validate_age(25, 18, 65) # true
# Codici e identificatori
validate_iban("IT60X0542811101000000123456") # true
validate_vat_code("12345678901") # true (IT)
validate_tax_code("RSSMRA80A01H501M") # true (IT)
validate_phone("+39 123 456 7890") # true
# Carte di credito
validate_credit_card("4111111111111111") # true
credit_card_type("4111111111111111") # "visa"
Funzioni File System
Gestione file e directory:
# Informazioni file
file_exists("path/to/file.txt") # true
is_file("path/to/file.txt") # true
is_dir("path/to/directory") # true
file_size("path/to/file.txt") # 1024 (bytes)
file_modified("path/to/file.txt") # timestamp
# Lettura file
file_read("config.txt") # contenuto completo
file_read_lines("data.txt") # array di linee
file_read_json("data.json") # parsed JSON
file_read_csv("data.csv") # array di record
# Scrittura file
file_write("output.txt", "content") # sovrascrive
file_append("log.txt", "new line") # aggiunge
file_write_json("data.json", data) # serializza JSON
file_write_csv("export.csv", records) # salva CSV
# Operazioni file
file_copy("source.txt", "dest.txt")
file_move("old.txt", "new.txt")
file_delete("temp.txt")
file_rename("old.txt", "new.txt")
# Directory
dir_create("new/directory")
dir_delete("old/directory")
dir_list("path/to/dir") # lista file/dir
dir_scan("path", "*.txt") # file per pattern
# Path utilities
path_join("home", "user", "file.txt") # "home/user/file.txt"
path_dirname("/home/user/file.txt") # "/home/user"
path_basename("/home/user/file.txt") # "file.txt"
path_extension("file.txt") # "txt"
path_filename("file.txt") # "file"
# Permessi (Unix-like)
file_permissions("file.txt") # "755"
file_readable("file.txt") # true
file_writable("file.txt") # true
file_executable("script.sh") # true
# Upload helper
upload_file(uploaded_file, "uploads/") # gestisce upload
upload_validate(file, ["jpg", "png"], 2048) # valida upload
Funzioni HTTP e Request
Gestione richieste HTTP e response:
# Request info
request_method() # "GET", "POST", etc
request_url() # URL completa
request_path() # path senza query
request_query() # query string
request_ip() # IP client
request_user_agent() # User-Agent header
# Input dati
input("name") # $_POST["name"] / $_GET["name"]
input("name", "default") # con valore default
input_get("param") # solo da GET
input_post("field") # solo da POST
input_json() # body JSON parsato
# Validazione input
input_required("email") # errore se mancante
input_email("email") # valida email
input_int("age", 0, 120) # valida e converte int
input_float("price") # valida e converte float
# Headers
request_header("Content-Type") # header specifico
request_headers() # tutti gli headers
has_header("Authorization") # controlla presenza
# Response
response_json(data) # risposta JSON
response_xml(data) # risposta XML
response_redirect("/login") # redirect
response_status(404) # imposta status
response_header("Cache-Control", "no-cache")
# Cookies
cookie_get("session_id") # legge cookie
cookie_set("user", "mario", 3600) # imposta cookie
cookie_delete("temp") # elimina cookie
# Session
session_start() # inizia sessione
session_get("user_id") # legge da sessione
session_set("user_id", 123) # scrive in sessione
session_destroy() # distrugge sessione
session_regenerate() # rigenera ID sessione
# File upload
uploaded_files() # lista file caricati
uploaded_file("avatar") # file specifico
upload_move("avatar", "uploads/") # sposta file caricato
# HTTP client
http_get("https://api.example.com")
http_post("https://api.example.com", data)
http_put("https://api.example.com", data)
http_delete("https://api.example.com")
Funzioni Database
Helper per query e operazioni database:
# Query builder shortcuts
db_select("users", where={"active": true})
db_insert("users", {"name": "Mario", "email": "mario@test.com"})
db_update("users", {"active": false}, where={"id": 123})
db_delete("users", where={"id": 123})
# Operazioni avanzate
db_count("users", where={"active": true})
db_exists("users", where={"email": "test@test.com"})
db_sum("orders", "total", where={"status": "completed"})
db_avg("reviews", "rating", where={"product_id": 123})
db_max("orders", "created_at")
db_min("products", "price")
# Transazioni
db_transaction():
db_insert("orders", order_data)
db_update("products", {"stock": stock - 1}, {"id": product_id})
# Raw queries sicure
db_query("SELECT * FROM users WHERE age > ?", [18])
db_execute("UPDATE stats SET views = views + 1 WHERE id = ?", [post_id])
# Paginazione
db_paginate("posts", page=1, per_page=10, where={"published": true})
# Relazioni rapide
db_with("users", "posts") # eager load relazioni
db_has("users", "posts") # solo utenti con posts
db_count_related("users", "posts") # conta posts per utente
# Cache query
db_remember("popular_posts", 3600): # cache per 1h
return db_select("posts", order="views DESC", limit=10)
# Validazione dati
db_validate_unique("users", "email", "test@test.com")
db_validate_exists("categories", "id", 123)
# Migration helpers
db_table_exists("new_table")
db_column_exists("users", "avatar")
db_index_exists("users", "email_index")
Funzioni Utility
Funzioni di utilità generale:
# Debug e logging
dump(variable) # output debug
dd(variable) # dump and die
log_info("User logged in") # log informativo
log_error("Database error") # log errore
log_debug("Query executed") # log debug
# Environment
env("DATABASE_URL") # variabile ambiente
env("DEBUG", false) # con default
is_production() # true se prod
is_development() # true se dev
is_testing() # true se test
# Configuration
config("database.host") # configurazione
config_set("cache.enabled", true)
config_has("redis.host")
# Hashing e crittografia
hash_password("mypassword") # hash sicuro
verify_password("plain", hash) # verifica password
generate_token(32) # token casuale
encrypt("sensitive data", key) # crittografia
decrypt(encrypted, key) # decrittografia
# UUID e ID
uuid() # UUID v4
uuid_short() # UUID corto
generate_id() # ID incrementale
slug_from("Hello World") # "hello-world"
# Cache
cache_get("key") # legge dalla cache
cache_set("key", value, 3600) # salva in cache (1h)
cache_forget("key") # rimuove dalla cache
cache_flush() # pulisce tutta la cache
cache_remember("expensive_op", 3600):
return expensive_operation()
# Rate limiting
rate_limit("api", 100, 3600) # 100 req/h
is_rate_limited("login", ip)
# Localizzazione
__("messages.hello") # traduzione
__("posts.count", count=5) # con parametri
locale() # lingua corrente
set_locale("it") # cambia lingua
# Helpers vari
retry(3): # riprova 3 volte
risky_operation()
sleep(2) # pausa 2 secondi
memory_usage() # memoria utilizzata
execution_time() # tempo esecuzione
app_version() # versione app
Funzioni Template Specifiche
Helper utilizzabili nei template Flux:
# URL generation
url("/about") # URL assoluta
route("users.show", user_id=123) # route nominale
asset("css/app.css") # asset con versioning
secure_url("/payment") # URL HTTPS
# Form helpers
form_open("users.store", method="POST")
form_text("name", value, {"class": "form-control"})
form_email("email", required=True)
form_password("password")
form_select("role", options, selected)
form_textarea("bio", value, rows=5)
form_checkbox("active", checked=True)
form_radio("plan", "premium", selected_plan)
form_file("avatar", accept="image/*")
form_submit("Salva", {"class": "btn btn-primary"})
form_close()
# CSRF e sicurezza
csrf_token() # token CSRF
csrf_field() # campo hidden con token
method_field("PUT") # field per method spoofing
# Auth helpers nel template
auth_user() # utente autenticato
auth_check() # true se autenticato
auth_guest() # true se guest
can("edit", post) # controllo permessi
# Paginazione
paginate(posts, show_numbers=5)
pagination_info(posts) # "Showing 1-10 of 50"
# Breadcrumbs
breadcrumb_add("Home", "/")
breadcrumb_add("Users", "/users")
breadcrumb_render()
# Meta tags
meta_title("Page Title")
meta_description("Page description")
meta_keywords("keyword1, keyword2")
meta_og_image("/images/social.jpg")
# Asset bundling
css_bundle(["app.css", "admin.css"])
js_bundle(["app.js", "components.js"])
inline_css(".highlight { color: red; }")
inline_js("console.log('Hello');")
# Conditional helpers
when(condition, "value_if_true", "value_if_false")
unless(condition, "value")
switch(variable, {
"case1": "value1",
"case2": "value2",
"default": "default_value"
})
Funzioni Personalizzate
Crea le tue funzioni riutilizzabili:
# app/functions.flux
# Funzione semplice
def greet(name):
return f"Ciao {name}!"
# Funzione con parametri opzionali
def format_price(amount, currency="€", decimals=2):
return f"{amount:.{decimals}f} {currency}"
# Funzione per template
def user_avatar(user, size="md"):
sizes = {"sm": 32, "md": 64, "lg": 128}
pixel_size = sizes.get(size, 64)
if user.avatar:
return f'<img src="{asset(user.avatar)}" width="{pixel_size}" alt="{user.name}">'
else:
return f'<div class="avatar-placeholder" style="width:{pixel_size}px;height:{pixel_size}px">{user.name[0]}</div>'
# Funzione con cache
@cache(minutes=10)
def popular_categories():
return Category.with_count('posts').order('posts_count', 'desc').take(5)
# Funzione di validazione
def validate_italian_phone(phone):
pattern = r"^(\+39|0039|39)?[\s\-]?([0-9]{2,3})[\s\-]?([0-9]{6,7})$"
return bool(re.match(pattern, phone))
# Helper per form
def country_options():
return {
"IT": "Italia",
"FR": "Francia",
"DE": "Germania",
"ES": "Spagna"
}
# Funzione per API
def send_notification(user, message, type="info"):
data = {
"user_id": user.id,
"message": message,
"type": type,
"created_at": now()
}
# Salva nel database
db_insert("notifications", data)
# Invia push notification
if user.push_enabled:
push_send(user.device_token, message)
return True
{# Uso nei template #}
<h1>{{ greet(user.name) }}</h1>
<p>Prezzo: {{ format_price(product.price) }}</p>
{{ user_avatar(user, "lg")|safe }}
{# Categorie popolari #}
{% for category in popular_categories() %}
<a href="{{ route('category.show', category.slug) }}">
{{ category.name }} ({{ category.posts_count }})
</a>
{% endfor %}
{# Select paesi #}
{{ form_select("country", country_options(), user.country) }}
Best Practices
🚀 Performance
- Cache risultati costosi
- Usa lazy loading quando possibile
- Evita N+1 queries
- Batch operations per molti dati
🔒 Sicurezza
- Valida sempre input utente
- Usa prepared statements
- Escapa output nei template
- Controlla permessi
📝 Manutenibilità
- Crea funzioni riutilizzabili
- Documenta parametri complessi
- Gestisci errori gracefully
- Testa le funzioni critiche
Esempio Completo: Sistema di Notifiche
# app/notifications.flux
def create_notification(user, type, title, message, data=None):
"""Crea una nuova notifica per l'utente"""
notification = {
"user_id": user.id,
"type": type, # info, success, warning, error
"title": title,
"message": message,
"data": json_encode(data) if data else None,
"read": False,
"created_at": now()
}
notification_id = db_insert("notifications", notification)
# Invia push se abilitato
if user.push_enabled and type in ["warning", "error"]:
send_push_notification(user, title, message)
# Invia email per notifiche critiche
if type == "error" and user.email_notifications:
send_email_notification(user, title, message)
return notification_id
def mark_as_read(user, notification_id=None):
"""Marca notifiche come lette"""
where = {"user_id": user.id}
if notification_id:
where["id"] = notification_id
return db_update("notifications", {"read": True}, where)
def get_user_notifications(user, unread_only=False, limit=20):
"""Recupera notifiche utente"""
where = {"user_id": user.id}
if unread_only:
where["read"] = False
return db_select("notifications",
where=where,
order="created_at DESC",
limit=limit)
@cache(minutes=5)
def unread_count(user):
"""Conta notifiche non lette (con cache)"""
return db_count("notifications",
where={"user_id": user.id, "read": False})
# Template helper
def notification_icon(type):
"""Icona per tipo notifica"""
icons = {
"info": "ℹ️",
"success": "✅",
"warning": "⚠️",
"error": "❌"
}
return icons.get(type, "📨")
def notification_class(type):
"""Classe CSS per tipo notifica"""
return f"notification notification-{type}"
# Funzione per inviare diverse tipologie
def notify_user_login(user, ip):
if is_suspicious_login(user, ip):
create_notification(user, "warning",
"Login Sospetto",
f"Accesso da IP sconosciuto: {ip}")
def notify_order_shipped(user, order):
create_notification(user, "info",
"Ordine Spedito",
f"Il tuo ordine #{order.id} è stato spedito!",
{"order_id": order.id, "tracking": order.tracking})
def notify_payment_failed(user, amount):
create_notification(user, "error",
"Pagamento Fallito",
f"Pagamento di {format_price(amount)} non riuscito")
{# Template usage #}
<div class="notifications-dropdown">
<button class="notification-toggle">
🔔
{% set count = unread_count(user) %}
{% if count > 0 %}
<span class="badge">{{ count }}</span>
{% endif %}
</button>
<div class="notifications-list">
{% for notification in get_user_notifications(user, limit=5) %}
<div class="{{ notification_class(notification.type) }}
{% if not notification.read %}unread{% endif %}">
<div class="notification-icon">
{{ notification_icon(notification.type) }}
</div>
<div class="notification-content">
<h4>{{ notification.title }}</h4>
<p>{{ notification.message }}</p>
<small>{{ date_human(notification.created_at) }}</small>
</div>
{% if not notification.read %}
<button onclick="markAsRead({{ notification.id }})">
✓
</button>
{% endif %}
</div>
{% else %}
<p class="no-notifications">Nessuna notifica</p>
{% endfor %}
{% if get_user_notifications(user)|length > 5 %}
<a href="{{ route('notifications.index') }}">
Vedi tutte
</a>
{% endif %}
</div>
</div>
🎯 Eccellente! Ora conosci tutte le funzioni built-in di Flux.
Esplora il Database per vedere come integrarle con i tuoi modelli.