PHPackages                             alphadevx/alpha - 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. [Framework](/categories/framework)
4. /
5. alphadevx/alpha

ActiveLibrary[Framework](/categories/framework)

alphadevx/alpha
===============

Alpha Framework is a full-stack MVC framework for PHP

4.0.0(2y ago)5155[41 issues](https://github.com/alphadevx/alpha/issues)[1 PRs](https://github.com/alphadevx/alpha/pulls)BSD-2-ClausePHPPHP &gt;=8.2.0

Since Feb 7Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/alphadevx/alpha)[ Packagist](https://packagist.org/packages/alphadevx/alpha)[ Docs](http://www.alphaframework.org/)[ RSS](/packages/alphadevx-alpha/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelogDependencies (6)Versions (21)Used By (0)

[![Install and unit tests](https://github.com/alphadevx/alpha/actions/workflows/php.yml/badge.svg)](https://github.com/alphadevx/alpha/actions/workflows/php.yml)[![codecov](https://camo.githubusercontent.com/152ada88416c41ce8b42d853d640d8300e105e517f4a2ea87aa8a4dae87a434d/68747470733a2f2f636f6465636f762e696f2f67682f616c706861646576782f616c7068612f6272616e63682f646576656c6f702f67726170682f62616467652e7376673f746f6b656e3d41534c334e4c44573146)](https://codecov.io/gh/alphadevx/alpha)

Alpha Framework (4.0.0)
=======================

[](#alpha-framework-400)

Introduction
------------

[](#introduction)

The Alpha Framework is a full-stack MVC framework for PHP. It provides the following features:

- A set of complex data types that have built-in validation checks, mappings to database field types, and UI widgets.
- An active record interface with support for MySQL and SQLite.
- A rendering interface with support for HTML and JSON (for developing APIs).
- A caching interface with support for APCu, Redis, and Memcache.
- A CRUD controller to take care of most of your data management needs.
- A front controller, abstract controller, and elegant request routing interface.
- Request/response classes.
- A full admin UI and installation UI.
- RSS and Atom feed generation.
- A built-in Markdown-based CMS with article voting and commenting.
- A built-in search engine with tagging support (including tag clouds, free-text search, find similar...).
- Strong security features (short-live form encryption tokens to prevent cross-site requests, encryption tokens on images to prevent cross-site embedding, HTTP request filters to block agents or IPs...).
- Complete logging solution, including optional user audit trail.
- Build-in application back-up task along with support for other, custom tasks.

Status
------

[](#status)

The current latest stable release is tested via unit testing and manual testing, and is considered suitable for production usage.

Installation
------------

[](#installation)

### Composer

[](#composer)

Alpha should be installed using Composer. Here is a minimum example *composer.json* file to install the current release:

```
{
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "alphadevx/alpha": "4.*"
    },
    "autoload": {
        "psr-0": {
            "": "src/"
        }
    },
    "scripts": {
        "post-update-cmd": [
            "cp -R vendor/twbs/bootstrap/dist/* public/bootstrap"
        ],
        "post-install-cmd": [
            "rm -rf public/bootstrap",
            "mkdir -p public/bootstrap",
            "cp -R vendor/twbs/bootstrap/dist/* public/bootstrap"
        ]
    }
}

```

### Database

[](#database)

Alpha stores its records in a relational database, currently MySQL and SQLite are supported via injectable providers (more will be written in the future). For SQLite, a file will be written to the filesystem based on your configuration (see the next section), but for MySQL you will need to manually create the database first:

```
MariaDB [(none)]> CREATE DATABASE alphaframework DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

```

You should also ensure that the MySQL user account that you are going to use to access that database has the correct rights granted to it.

### Configuration

[](#configuration)

Alpha configuration is broken down into three deployment envrionments, which in turn have their own config files:

NameDescriptionConfig filedevYour developer environment (localhost).config/dev.initestYour test environment for QA/UAT testing.config/test.iniproYour production environment.config/pro.iniFrom the *vendor* directy created by Composer, you should copy those files into your application root directory:

```
$ cp -R vendor/alphadevx/alpha/config .

```

Alpha chooses the correct file to load based on the hostname of the current server. That hostname to config environment mapping occurs in the *config/servers.ini* file. Here is an example of that file:

```
; The server names for the three environments
dev = localhost,alphaframework.dev
pro = alphaframework.org
test = unittests,qa.alphaframework.org

```

Multiple server hostnames can be added per environment, seperated by commas.

The config files themselves are well-commented, but here is a list of the minimum settings you should configure before continuing with your installation:

SettingDescriptionapp.urlSystem root URL.app.rootThe OS root directory.app.file.store.dirThe path to the directory where files are stored (logs, attachments, cached files etc.).app.titleThe title of the web site.db.nameThe name of the main database to use.db.usernameDatabase username.db.passwordDatabase password.db.hostnameDatabase host.security.encryption.keySecret key used for encryption when using the SecurityUtils class.app.install.usernameUsername used for admin access during intallation when creating the database.app.install.passwordPassword used for admin access during intallation when creating the database.Please review the comments in the config files for addition optional settings.

### Bootstrap

[](#bootstrap)

Alpha uses a front controller to route all traffic to a single physical file in your web server configuration. That file, *index.php*, is contained with the *public* directory of the framework. Copy that directory into the root of your application:

```
$ cp -R vendor/alphadevx/alpha/public .

```

Now open that file in your editor to review: it is this file that you will use to add in customer routes to your custom controllers. You will then need to configure your web server to send all traffic to your *public/index.php* file (with the exception of static files that are also in *public*), here is an example Apache virtual host configuration:

```

   DocumentRoot "/home/john/Git/alphaframework/public"
   ServerName alphaframework.dev

      Options FollowSymLinks
      Require all granted

      RewriteEngine On
      RewriteBase /
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{DOCUMENT_ROOT}/index\.php -f
      RewriteRule ^(.*)$  /index.php?page=$1 [QSA]

```

### Running the installer

[](#running-the-installer)

Once you have configured your application, your web server, and created an empty database, you should then start up you web and database servers and navigate to the root URL of your application. Alpha will automatically detect that it is not installed, and will re-direct to the *Alpha\\Controller\\InstallController* for you.

The first thing you will see is a prompt for a username and password, you should enter the values for *app.install.username* and *app.install.password* from your application config file to gain access.

The InstallController will create any directories required for you (to store log files, the file cache, article attachments etc.), in addition to creating the database tables, indexes, and foreign keys required to support our active records. Once all of this work is completed, a link to the administration backend will be presented.

Once your application is installed in production, you should set the *app.check.installed* config value to false to remove the overhead of checking to see if the application is installed on each request.

Models
------

[](#models)

### Data types

[](#data-types)

The model layer of Alpha consists of an active record implementation, and a set of data types. The data types are designed to map to corresponding database types seamlessly, as well as providing validation and frontend widgets. The following data types are included:

TypeSizeValidation rulesDescriptionAlpha\\Model\\Type\\Boolean11/0 or true/false.A boolean value.Alpha\\Model\\Type\\Enum-One of the items from the list.A fixed listed of strings to choose from, e.g. weekdays, gender etc.Alpha\\Model\\Type\\DEnum-ID for one of the items from the list.A Dynamic Enum, allows you to modify the elements in the enum as stored in the database.Alpha\\Model\\Type\\Date10A date in ISO YYYY-mm-dd format.A date value.Alpha\\Model\\Type\\Timestamp19A timestamp YYYY-mm-dd hh:ii:ss.A timestamp value.Alpha\\Model\\Type\\Double13A valid double value.A double value.Alpha\\Model\\Type\\Integer11A valid integer value.An integer value.Alpha\\Model\\Type\\Relation11ID of the related record, or empty.A relation type supporting MANY-TO-ONE, ONE-TO-MANY, ONE-TO-ONE, MANY-TO-MANY types.Alpha\\Model\\Type\\Sequence255Sequence in format PREFIX-00000000000.A database sequence number with a string prefix defined by the developer.Alpha\\Model\\Type\\SmallText255A small text value.A small text value (single line).Alpha\\Model\\Type\\Text65535A large text value.A large value (paragraphs).### ActiveRecord

[](#activerecord)

An active record then uses these data types to store the attributes of an object we care about in the database. For example, here is how our *Person* active record makes use of these complex types:

```
 items in your shopping cart.

```

### Widgets

[](#widgets)

Alpha provides a number of HTML widgets in the *Alpha\\View\\Widget* package, that are very convenient for renderer nice interfaces quickly using Twitter Bootstrap CSS and addition JQuery code.

The following widgets are included:

Widget classDescriptionParamtersAlpha\\View\\Widget\\ButtonA Bootstrap button.Some Javascript to execute when the button is pressed.Alpha\\View\\Widget\\DateBoxA Bootstrap date picker.An Alpha\\Model\\Type\\Date or Alpha\\Model\\Type\\Timestamp instance.Alpha\\View\\Widget\\ImageA scaled, secure image.The source path of the original file along with desired dimensions.Alpha\\View\\Widget\\RecordSelectorUsed for relating records.A *Alpha\\Model\\Type\\Relation* instance.Alpha\\View\\Widget\\SmallTextBoxOne-line text input box.A *Alpha\\Model\\Type\\SmallText* instance.Alpha\\View\\Widget\\TextBoxMulti-line text input box.A *Alpha\\Model\\Type\\Text* instance.Alpha\\View\\Widget\\TagCloudA cloud of popular tags.The maximum amount of tags to include in the cloud.Utils
-----

[](#utils)

Alpha includes many varied utilities in the *Alpha\\Util* package. The following sections cover some of the highlights.

### Cache

[](#cache)

A data cache is provided, that provides a factory and injectable providers that support Memcache, Redis, and APCu. The classes are provided in the *Alpha\\Util\\Cache* package, while the providers implement the *Alpha\\Util\\Cache\\CacheProviderInterface*. Here is an example using the Redis provider:

```
use Alpha\Util\Service\ServiceFactory;

// ...

$cache = ServiceFactory::getInstance('Alpha\Util\Cache\CacheProviderRedis','Alpha\Util\Cache\CacheProviderInterface');
$record = $cache->get($cacheKey);

```

### Code highlighting

[](#code-highlighting)

The *Alpha\\Util\\Code\\Highlight\\HighlightProviderFactory* providers objects for converting plain source code into code-highlighted HTML source code. Providers for the Geshi and Luminous libraries are provided. Here is an example:

```
use Alpha\Util\Service\ServiceFactory;

// ...

$highlighter = ServiceFactory::getInstance('Alpha\Util\Code\Highlight\HighlightProviderGeshi','Alpha\Util\Code\Highlight\HighlightProviderInterface');

$html = $highlighter->highlight($code, 'php');

```

### Email

[](#email)

Alpha provides an email package with an interface for injecting different email providers. Here is an example usage:

```
use Alpha\Util\Service\ServiceFactory;
use Alpha\Exception\MailNotSentException;

// ...

$mailer = ServiceFactory::getInstance('Alpha\Util\Email\EmailProviderPHP','Alpha\Util\Email\EmailProviderInterface');

try {
	$mailer->send('to@mail.com', 'from@mail.com', 'Subject', 'Some HTML...', true);
} catch (MailNotSentException $e) {
	// handle error...
}

```

### Feeds

[](#feeds)

Alpha can generate an Atom, RSS, or RSS2 feed based on a list of active records, using the classes in the *Alpha\\Util\\Feed* package. The *FeedController* is also provided for convience, that has the following route already set-up in the *FrontController*:

```
$this->addRoute('/feed/{ActiveRecordType}/{type}', function ($request) {
    $controller = new FeedController();

    return $controller->process($request);
})->value('type', 'Atom');

```

If you want to use the feed classes directly in your application, you can do so:

```
use Alpha\Util\Feed\Atom;

// ...

$feed = new Atom($ActiveRecordType, $title, $url, $description, $pubDate, $ID);
$feed->setFieldMappings('title', 'URL', 'description', 'created_ts', 'ID');
$feed->addAuthor('Feed author');
$feed->loadRecords(20, 'ID');

$xml = $feed->render();

```

### Validation

[](#validation)

A validation class is provided for handling typical type checks or for testing for common string patterns (email address, URLs etc.). The class in question is *Alpha\\Util\\Helper\\Validator*, check the *Alpha\\Test\\Util\\Helper\\ValidatorTest* unit test for lots of code examples on how to use this class.

### HTTP

[](#http)

#### Filters

[](#filters)

Alpha provides a framework for injecting optional request filters into the front controller, that are run before any request in routed through there. You can write your own filters that implement the *Alpha\\Util\\Http\\Filter\\FilterInterface*, in addition Alpha provides the following build-in filters that you can choose to enable:

FilterPurposeAlpha\\Util\\Http\\Filter\\ClientBlacklistFilterBlock any request from a client matching the blacklisted User-Agent.Alpha\\Util\\Http\\Filter\\IPBlacklistFilterBlock any request from a client matching the blacklisted IP.Alpha\\Util\\Http\\Filter\\ClientTempBlacklistFilterBlock too many requests from a given client/IP compination for a short period.Registering a filter with the front controller is easy, and should be done on application bootstrap, typlically in your index.php file:

```
use Alpha\Controller\Front\FrontController;
use Alpha\Util\Http\Filter\ClientBlacklistFilter;
use Alpha\Exception\ResourceNotAllowedException;

// ...

try {
	$front = new FrontController();
	$front->registerFilter(new ClientBlacklistFilter());
} catch (ResourceNotAllowedException $e) {
	// the filters will throw this exception when invoked so you will need to handle, e.g. send 403 response.
}

```

#### Sessions

[](#sessions)

Alpha provides a session abstraction layer to allow the inject of different session providers, which is very useful for example if you want to store your session in an array for unit testing. It is also possible to write providers to store sessions in NoSQL or database backends. Here is an example of using the default PHP session mechanism:

```
use Alpha\Util\Service\ServiceFactory;

// ...

$session = ServiceFactory::getInstance('Alpha\Util\Http\Session\SessionProviderPHP', 'Alpha\Util\Http\Session\SessionProviderInterface');
$session->set('somekey', 'somevalue'); // you can also pass complex types
echo $session->get('somekey');

```

#### Request and Response

[](#request-and-response)

Rather than working with PHP super-globals such as \_GET and \_POST directly, Alpha provides Request and Response classes in the *Alpha\\Util\\Http* package to encapsulate those globals.

The attributes of the Request objects (HTTP headers, HTTP verbs, request body etc.) are set during the object instantiation via the \_\_construct($overrides) method, based on the available super-global values. Note that you can override any of the super-global values via the $overrides hash array parameter, which is useful for unit testing.

The Response constructor expects a HTTP response code, body, and optional array of HTTP headers during construction. Here is an example:

```
use Alpha\Util\Http\Response;

// ...

$response = new Response(200, 'hello world!', array('Content-Type' => 'text/html'));
$response->send();

```

### Logging

[](#logging)

A logging class is provided with a standard set of methods for logging at different levels:

```
use Alpha\Util\Logging\Logger;

// ...

$logger = new Logger('ClassName');
$logger->debug('Debug information');
$logger->info('Notable information');
$logger->warn('Something went wrong');
$logger->error('A serious error');
$logger->fatal('A fatal error');
$logger->sql('SELECT * FROM...');
$logger->action('Action carried out by the current user logged in the ActionLog table');

```

The log that is written to is defined by the following configuration properties:

```
$config->get('app.file.store.dir').'logs/'.$config->get('app.log.file');

```

Alpha also provides a KPI class, or *Key Performance Indicator*, that is useful for logging time-sensitive entries that can indicate how your application is performing in production. Here is an example usage:

```
use Alpha\Util\Logging\KPI;

// ...

$KPI = new KPI('KPIName');
// ...
$KPI->logStep('something happened');
// ...
$KPI->logStep('something else happened');
// ...
$KPI->log();

```

Each KPI is logged, along with timings and session IDs, in a seperate log file in the following location:

```
$config->get('app.file.store.dir').'logs/kpi-'.$KPIName.'.csv';

```

### Search

[](#search)

A simple search engine is provided to use in your applications, that is made up of a seach controller and an abstract search API on the backend that searches the main active record database for matching records, based on tags attached to those records.

The key classes are:

ClassDescriptionAlpha\\Controller\\SearchControllerHandles search queries sent via HTTP requests.Alpha\\Util\\Search\\SearchProviderInterfaceThe main search API.Alpha\\Util\\Search\\SearchProviderTagsImplements the SearchProviderInterface using Tag active records.Alpha\\Model\\TagContains a simple string value that helps to describe the related active record.Alpha\\Controller\\TagControllerUsed to edit tags on a single record, and manage all tags in the admin backend.A typical use case is contained in the content management system included with Alpha. When an Article record is saved, a callback is used to generate a set of Tag records based on the content of the Article (excluding stop-words contained in the *stopwords-large.ini* or *stopwords-small.ini* files), and those Tag records are related to the Article via a ONE-TO-MANY Relation type, and saved to the main database. Searches are then conducted against the Tag table, and once matching Tags are found we load the related Article records.

For example code, please view the *Alpha\\Controller\\SearchController* class and the *Alpha\\Test\\Controller\\SearchControllerTest* and *Alpha\\Test\\Util\\Search\\SearchProviderTagsTest* unit tests.

### Security

[](#security)

Alpha provides a static utility class with two methods for encrypting or decrypting data:

```
use Alpha\Util\Security\SecurityUtils;

// ...

$encrypted = SecurityUtils::encrypt('Some data');
$decrypted = SecurityUtils::decrypt($encrypted);

```

The class makes use of the OpenSSL extension in PHP to handle encryption, using the AES 256 algorithm. The secret key used is what you set in the *security.encryption.key* setting in your config file, which is unique to your application.

### Error handling

[](#error-handling)

It is best practice to build in your own error handling into your application using try/catch blocks, however in the event of an uncaught exception or a generic (non-fatal) PHP error, Alpha provides the *Alpha\\Util\\ErrorHandlers* class that should be used in your bootsrap file like so:

```
set_exception_handler('Alpha\Util\ErrorHandlers::catchException');
set_error_handler('Alpha\Util\ErrorHandlers::catchError', $config->get('php.error.log.level'));

```

The *catchException()* method captures an uncaught Exception object and logs it to the application log (message and stacktrace). The *catchError()* method captures a general PHP error and converts it to an *Alpha\\Exception\\PHPException* object, which is then thrown to be captured and logged by *catchException()*.

Contact
-------

[](#contact)

For bug reports and feature requests, please e-mail:

On Twitter: [@alphaframework](https://twitter.com/alphaframework)

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity85

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 99.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~195 days

Recently: every ~507 days

Total

16

Last Release

810d ago

Major Versions

2.0.4 → 3.0.0-RC.12018-05-19

3.x-dev → 4.0.02024-02-19

PHP version history (6 changes)2.0.0PHP &gt;=5.5.0

3.0.0-RC.1PHP &gt;=7.0.0

3.0.0-RC.2PHP &gt;=7.2.0

3.1.0PHP &gt;=7.3.0

3.x-devPHP &gt;=7.4.0

4.0.0PHP &gt;=8.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/c4eb7696617485bbe0051a4239c8353faae6b4a1ba486d035a6b8629755a2b71?d=identicon)[alphadevx](/maintainers/alphadevx)

---

Top Contributors

[![alphadevx](https://avatars.githubusercontent.com/u/5739179?v=4)](https://github.com/alphadevx "alphadevx (2942 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (5 commits)")

---

Tags

httpframeworkrestmvcfullstack

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/alphadevx-alpha/health.svg)

```
[![Health](https://phpackages.com/badges/alphadevx-alpha/health.svg)](https://phpackages.com/packages/alphadevx-alpha)
```

###  Alternatives

[gregurco/guzzle-bundle-cache-plugin

Cache Plugin for Guzzle Bundle, a PHP HTTP client library and framework for building RESTful web service clients

11372.1k1](/packages/gregurco-guzzle-bundle-cache-plugin)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
