Download the PHP package reves/val without Composer
On this page you can find all versions of the php package reves/val. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package val
val
val is a PHP web framework mainly for single page applications.
Requirements
- PHP >= 8.3
- Composer
- Mbstring PHP Extension
- Sodium PHP Extension
Out of the box compatibility
- Databases: SQLite, PostgreSQL, MySQL / MariaDB
- Servers: Apache, Nginx
Table of contents:
- Installation
- How it works
- Conventions
- CLI
- Configuring the server
- Configuring the app and environments
- Serving the View
- Creating an API
- Migrations
- Documentation
Installation
1. Add to composer.json the following script that will automatically create the CLI tool on installation.
2. Run the installation.
How it works
Usage example in public/index.php:
The entry point of the application is the static method Val\App::run(), which is called in index.php. This method processes two types of requests:
1. API Requests
API requests are either POST or GET, and they require the _api parameter to be present in the request URL (e.g. /index.php?_api=books). When this parameter is detected, the framework will use the corresponding API class located in your application's api/ directory (e.g. api/Books.php).
In this case the application acts as an API provider, responding with raw JSON data and appropriate HTTP status codes. For API client convenience on frontend, the server should have rewrite rules configured to handle clean URLs, such as /api/books.
2. View Requests
For all non-API requests, the application serves the View, which is simply an anonymous function passed as the first parameter to App::run(). For example, this function may return HTML of a single-page application, where routing is handled on the client-side.
Conventions
Root directory structure
api/– Contains API classes.config/– Application and environment configuration files.migrations/– Database migration classes.public/– The directory exposed to the internet, containing theindex.phpentry point.vendor/– Dependencies managed by Composer.view/– Contains templates for the View function or email templates..gitignore– (!) Important: Ensure files likeconfig/env.*are added.val(orval.baton windows) – The CLI tool used for app files creation and migration management.
Timezone
Timezone defaults to UTC.
CLI
The val file, located in the root directory of the app, represents the CLI tool. It helps with files creation and database migration management.
Commands:
val or val help
Lists all the available commands.
val create
Creates all the necessary directories and files for the app to function. Useful command especially for new projects.
Subcommands of val create:
-
val create config <name>– Creates a specific config file. E.g.val create config geolocationwill create theconfig/geolocation.phpfile. If the<name>is not specified, will create a config file namedconfig/config.php.The
app,auth,db,envorenvdevconfig names are reserved and will use a built-in template for creation. -
val create api <name>– Creates a specific API class. E.g.val create api Bookswill create theapi/Books.phpfile. If the<name>is not specified, will create an API class file namedapi/Test.php. -
val create migration <name>– Creates a new migration class. E.g.val create migration CreateBooksTablewill create themigrations/id_CreateBooksTable.php. If the<name>is not specified, will create a migration class file namedmigrations/id_NewMigration.php.The migration name
CreateSessionsTableis reserved and will use a built-in template for creation. val create appkey– Creates theconfig/env.dev.phpenv config file with a generated app key or, if the file already exists, regenerates the current app key in that file. This command will not change the app key in theconfig/env.php(production env config).
val migrate <version> [-y/--yes]
Runs all migrations till (including) the specified version number. E.g. val migrate 5 will call consecutively all up() methods of the new migrations where id <= 5. If the <version> is not specified, will attempt to migrate to the latest available version.
(!) This command asks for confirmation [y/n] before proceeding.
val rollback <version> [-y/--yes]
Rollbacks all migrations until (excluding) the specified version number. E.g. val rollback 3 will call consecutively all down() methods of the applied migrations where id > 3. If the <version> is not specified, will attempt to rollback the latest applied version.
(!) This command asks for confirmation [y/n] before proceeding.
Configuring the server
Apache
The val create command will create an .htaccess file in /public directory.
Nginx
[TODO]
Configuring the app and environments
Environment
The environment configuration files are the two config files with reserved names config/env.php and config/env.dev.php. At least one of these two files is required, to run the application.
env.php– Production environment configuration file.env.dev.php– Development environment configuration file. If this file is present, it takes precedence overenv.php, so the environment becomes of development. If this file is missing, the default environment is production.
Environment-dependant side effects:
- The
display_errorsini setting is set tofalsein production environment.
App configurations
The main app configuration files are the config files located in the config/ folder.
Reserved config file names:
Serving the View
[TODO] (meanwhile, read App class)
Creating an API
[TODO] (meanwhile, read Api class)
Migrations
[TODO] (meanwhile, read CLI)
Documentation
- App class
- Api class
- App-related modules
- Api-related modules
App class Val\App
The App class manages the application runtime.
Usage
App::run(?\Closure $view = null, ?string $rootPath = null) : void
The method run() represets the application entry point and initializes all modules, directory paths and specific response headers, then runs the API/View (depending on request type).
App::isApiRequest() : bool
App::isProd() : bool
App::exit() : never
Api class Val\Api
The Api class offers request/response management for application's API classes. In other words, classes in the api/ directory should extend the Api class (unless a specific API class manages the request/response process in a custom way).
Functionality
- Setting request requirements for a specific method (endpoint):
- the allowed request method: only POST / only GET / both (default).
- authentication: only Authenticated users / only Unauthenticated users / both (default).
- required field(s).
- optional field(s).
- Validation/Pre-processing of field values – automatic calls to corresponding methods (if defined, e.g.
ApiName::validate<Fieldname>(&$value)), based on specified required/optinal field(s). - Response structuring:
- preparing a common error response, by setting
setInvalid()for each field with invalid data. - automatically sent
400response, if any missing or invalid fields, after all validation methods calls. The error-related data is included in the response. - successful response
200, with/without response data. - custom error
400...500response.
- preparing a common error response, by setting
Usage
Api::__invoke()
This method represents the default endpoint of a specific API (e.g. example.com/api/books).
By default, this method is empty and returns a 404 response.
GET /api/books - 200 OK
Api::peek(string $endpoint, array $params = []) : mixed
This method makes an internal call to any application API in a "frontend-like" format.
GET /api/books/byauthor?author=John+Doe - 200 OK
(notice the author parameter, which is required)
Can be used from the View function as well:
Api::onlyGET() : self
Allows only GET requests to this API action method.
Api::onlyPOST() : self
Allows only GET requests to this API action method.
Api::onlyAuthenticated() : self
Allows only Authenticated users to call this API action method.
Api::onlyUnauthenticated() : self
Allows only Unauthenticated users to call this API action method.
Api::required(string|array ...$fields) : self
Registers the required (mandatory) fields for this API action method. Also, calls the corresponding validation method (if defined) for each field.
(!) Fields with empty "" values are NOT considered as missing, so remember to check for length (when validating), if needed.
POST /api/<api-name>/list?author=John+Doe&title= - 400 Bad Request
Validation:
POST /api/<api-name>/addComment - 400 Bad Request
Grouping fields in arrays, to use the same validation method:
Api::optional(string|array ...$fields) : self
Works the same way as Api::required does, except it doesn't list these fields as missing if they're not specified in the request. Also calls the corresponding validation method for each field (if defined).
Api::val(string $field) : mixed
Returns the value of the specified field.
Api::setInvalid(string $field, string $status, ?array $params = null) : self
Manually adds to the final error response an "invalid" message for a specific field.
Api::success(?array $data = null) : array|bool
Api::error(int $code = 500, ?string $status = null) : never
Responds with an error. This methods is also used internally in the process of fields validation.
If the requirements like onlyPOST or onlyAuthenticated are met (if any), then the following error messages will appear (if any) in the response body, in JSON format, in the following order, one at a time:
missing 400 --> invalid 400 --> status <status-code> (custom error)
With a custom status/message:
POST /api/<api-name>/addImage - 500 Internal Server Error
App-related modules
The App-related modules are used internally in the framework, also may be used in the application's APIs or in the View as well.
The modules initialized by default are: Lang, CSRF, DB, Auth, Renderer. Although the modules Lang, DB and Auth require certain configs to work.
- Auth
- Config
- Cookie
- Crypt
- CSRF
- DB
- HTTP
- JSON
- Lang
- Renderer
- Token
- UUID
Auth Val\App\Auth
The Auth module allows to:
- Authenticate the user account - checks whether the session token is genuine and not expired/revoked.
- Manage account's sessions (on multiple devices).
(!) The account creation/confirmation/management, access authorization, roles and other... will be managed by application's custom APIs which will use the framework's Auth module just as a sessions management library.
(!) The accountId is expected to be of UUIDv7 format (use the Val\App\UUID module for generation).
Configs config/auth.php (required)
- (optional)
session_lifetime_days => 365– The session will permanently expire after this duration (in days).- Default:
Auth::SESSION_LIFETIME_DAYS
- Default:
- (optional)
session_max_offline_days => 7– The session will expire if the device remains inactive for this duration (in days).- Default:
Auth::SESSION_MAX_OFFLINE_DAYS
- Default:
- (optional)
token_trust_seconds => 5– Duration (in seconds) to trust the session token before re-checking in the database if the session still remains valid.- Default:
Auth::TOKEN_TRUST_SECONDS
- Default:
- (optional)
session_update_seconds => 60– The "last seen" data is updated in the database no more frequently than this duration (in seconds).- Default:
Auth::SESSION_UPDATE_SECONDS
- Default:
-
(optional)
max_active_sessions => 30– The maximum number of active sessions per account.- Default:
Auth::MAX_ACTIVE_SESSIONS
- Default:
- Other configs:
config/db.php(required), and the defaultCreateSessionsTablemigration applied (use the CLI).config/app.php(required).
Usage
Auth::initSession(string $accountId) : bool
Initializes a new session for a given accountId (UUID). Returns true on success, or false on error or if too many active sessions.
Auth::revokeSession(?string $id = null) : bool
Revokes the authentication session by a given session UUID. If no parameter given, revokes the current session. Returns true on success, or false if the session is not found in the database.
Auth::revokeAllSessions() : bool
Revokes all the sessions of the current user. Returns true on success, or false if no sessions were found in the database.
Auth::revokeOtherSessions() : bool
Revokes all the sessions of the current user, except the current session. Returns true on succes, or false if no other sessions were found in the database.
Auth::removeExpiredSessions(string $accountId) : bool
Removes all the expired sessions of a given account UUID from the database. Returns true on success, or false if no expired sessions were found in the database.
(!) This method is automatically called on every Auth::initSession() call.
Auth::getAccountId() : ?string
Returns the accountId (UUID) associated with the current session, or null if the user is unauthenticated.
Auth::getSignedInAt() : ?string
Returns the dateTime the session was initialized.
Auth::getLastSeenAt() : ?string
Returns the dateTime the session data updated.
Auth::getSignedInIPAddress() : ?string
Returns the IP address of the session initialization.
Auth::getLastSeenIPAddress() : ?string
Returns the IP address of the session update.
Auth::getIPAddress() : ?string
A helper static method that returns the client's IP address, or null if unable to determine.
Config Val\App\Config
The Config module allows to get a config/env value by specifying the config name and the field name.
Usage
Config::<config_name>(string $name) : mixed
The dynamic <config_name> method stands for the config file name and the $name parameter stands for the field name inside the config file.
Cookie Val\App\Cookie
Usage
Cookie::isSet(string $name) : bool
Cookie::get(string $name) : string
Cookie::set(string $name, string $value = '', array $options = []) : bool
Cookie::unset(string $name) : bool
Cookie::setForDays(string $name, string $value = '', int $days = 1, array $options = []) : bool
Cookie::setForMinutes(string $name, string $value = '', int $minutes = 1, array $options = []) : bool
Cookie::setForSeconds(string $name, string $value = '', int $seconds = 1, array $options = []) : bool
Crypt Val\App\Crypt
Configs config/app.php (required)
- (required)
key => 'app-key'– required for this module to work.
Usage
Crypt::encrypt(?string $message) : ?string
Crypt::decrypt(string $encodedEncryptedMessage) : ?string
CSRF Val\App\CSRF (internal)
The CSRF module is automatically applied for the API methods which have $this->onlyPOST() set.
Configs config/app.php (required)
- (required)
key => 'app-key'– required for encryption.
DB Val\App\DB and Val\App\DBDriver
The DB module wraps the PDO interface and makes it easier to use.
Configs config/db.php (required)
- (optional, but recommended)
driver => DBDriver::MySQL– the database driver.DBDriver::MySQL(default) – MySQL, compatible with MariaDB.DBDriver::PostgreSQL– PostgreSQL.DBDriver::SQLite– SQLite.
- For SQLite driver:
- (required)
path => App::$DIR_ROOT . '/db.sqlite3'– Path to database.
- (required)
- For MySQL or PostgreSQL driver:
- (required)
'host' => '127.0.0.1'– Database host. - (required)
'db' => 'myapp'– Database name. - (required)
'user' => 'root'– Database user. - (required)
'pass' => ''– Database user password.
- (required)
Usage
DB::beginTransaction() : bool
DB::commit() : bool
DB::rollback() : bool
DB::transactionIsActive() : bool
DB::raw(string $query) : int|bool
(!) Data inside the query should be properly escaped.
Executes an SQL statement with a custom query. This method cannot be used with any queries that return results. Returns the number of rows that were modified or deleted, or false on error.
DB::lastInsertId() : string
(!) In case of a transaction, should be used before DB::commit().
Returns the id string of the last inserted row.
DB::rowCount() : int
(!) Not recommended to use with SELECT statements.
Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement.
DB::prepare(string $query) : self
DB::bind(string|int $placeholder, bool|float|int|string|null $value) : self
DB::bindPlaceholder(bool|float|int|string|null $value) : self
DB::bindMultiple(array $relations) : self
DB::execute(?array $relations = null) : bool
DB::single(?array $relations = null) : ?array
DB::resultset(?array $relations = null) : array
DB::generatePlaceholders(int $count) : string
Helper method to generate question marks to include into a query.
DB::dateTime(?int $timestamp = null) : string
Returns a dateTime string matching the ISO 8601 "YYYY-MM-DD hh:mm:ss" format.
DB::close() : void
Closes the database connection. The framework closes the connection automatically on API response, so it's not mandatory to use this method.
HTTP Val\App\HTTP
Usage
HTTP::get(string $url, array $parameters = []) : ?array
HTTP::post(string $url, array $parameters = []) : ?array
JSON Val\App\JSON
Usage
JSON::encode(array $data) : ?string
JSON::decode(?string $json) : ?array
Lang Val\App\Lang
The Lang module detects the user preferred language, or sets a specific language for the user. Optionally, manages the language code in the URL path.
Language code format: <ISO 639 language code>[-<ISO 3166-1 region code>]
Configs config/app.php (optional)
- (optional)
languages => ['fr', 'en', ...]– a list of supported languages (e.g. if not specified in the list, the detecteden-USwill fallback toen). - (optional)
language_in_url => true|false– whether to manage the language code in the URL path.
Detection precedence
- From
langcookie (which was set previously, if it's not the first user's request). - From 'Accept-Language' header.
- Default supported language (the first one in the
Config::app('languages')list), if the list is set.
Usage
Lang::get() : ?string
Returns the detected language code, or null if the language couldn't be detected.
Lang::set(string $code) : bool
Returns false, if the language code has an invalid format or an error occurred while setting the lang cookie, otherwise true.
Renderer Val\App\Renderer
Renderer module allows to:
- Load a template file with a custom extenstion (.tpl, .html, ...).
- Minify the loaded template by removing the following characters:
[\r\n\t] 1+,<space> 2+,HTML comments - Insert other template's content, e.g.
{@header/nav.html}. - Bind data to placeholders, e.g.
{title},{content}. - Reveal blocks (the blocks are removed from the result if not "revealed"), e.g.
[in_stock]Product in stock![/in_stock].
For convenience, static methods of the Renderer class return an instance of this class (singleton), so the "template-processing" methods can be further chained using the -> operator.
Example templates
Usage
Renderer::setPath(string $directoryPath) : self
Renderer::load(string $file, bool $minify = true) : self
Result:
Renderer::bind(string $binding, string $value = '') : self
Renderer::bindMultiple(array $relations) : self
Renderer::reveal(string $block) : self
Renderer::revealMultiple(array $blocks) : self
Renderer::getContent() : string
Returns the rendered content of the loaded template.
Token Val\App\Token
Token module helps to manage custom tokens which represent some data encoded in JSON format and then encrypted by using the application key. Useful for encrypting and storing custom data in the cookies or local storage.
Configs config/app.php (required)
- (required)
key => 'app-key'– required for encryption.
Usage
Token::create(array $data) : ?string
Token::extract(string $token) : ?array
Token::expired(string $createdAt, int $timeToLive, string $timeScale) : bool
Checks if a token has expired based on creation time and time to live (TTL). The time scale for TTL must be specified using one of the class constants: Token::TIME_SECONDS, Token::TIME_MINUTES, Token::TIME_HOURS, Token::TIME_DAYS.
UUID Val\App\UUID
Usage
UUID::generate() : ?string
API-related modules
Val\Api\{...}
The API-related modules are used primarily in api/ classes.
- Two-Factor authentication
- Captcha
TwoFactorAuth Val\Api\TwoFactorAuth
Usage
TwoFactorAuth::generateSecretKey() : ?string
TwoFactorAuth::createURI(string $secretKey, string $appName, string $accountName) : string
TwoFactorAuth::verify(string $secretKey, string $code) : bool
Captcha Val\Api\Captcha
Usage
Turnstile (Cloudflare)
Captcha::Turnstile(string $secret, string $response) : ?array
hCaptcha (Intuition Machines)
Captcha::hCaptcha(string $secret, string $response, ?string $sitekey = null) : ?array
Example using config/app.php and config/env.php for storing the secret key.
reCAPTCHA (Google)
Captcha::reCAPTCHA(string $secret, string $response) : ?array
Mail Val\Api\Mail
Mail module uses the standard mail() function that provides the very basic functionality. In a real application, it is recommended to use any popular library for email sending.
Usage
Mail::send(array $options) : bool
All versions of val with dependencies
ext-mbstring Version *
ext-sodium Version *