PHP code example of alphadevx / alpha

1. Go to this page and download the library: Download alphadevx/alpha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alphadevx / alpha example snippets



	namespace Alpha\Model;

	// ...

	class Person extends ActiveRecord
	{
	    /**
	     * The forum display name of the person.
	     *
	     * @var \Alpha\Model\Type\SmallText
	     *
	     * @since 1.0
	     */
	    protected $username;

	    /**
	     * The email address for the person.
	     *
	     * @var \Alpha\Model\Type\SmallText
	     *
	     * @since 1.0
	     */
	    protected $email;

	    /**
	     * The password for the person.
	     *
	     * @var \Alpha\Model\Type\SmallText
	     *
	     * @since 1.0
	     */
	    protected $password;

	    // ...

	    /**
	     * An array of data display labels for the class properties.
	     *
	     * @var array
	     *
	     * @since 1.0
	     */
	    protected $dataLabels = array('ID' => 'Member ID#',
	                                    'username' => 'Username',
	                                    'email' => 'E-mail Address',
	                                    'password' => 'Password',
	                                    'state' => 'Account state',
	                                    'URL' => 'Your site address',
	                                    'rights' => 'Rights Group Membership',
	                                    'actions' => 'Actions', );
	    /**
	     * The name of the database table for the class.
	     *
	     * @var string
	     *
	     * @since 1.0
	     */
	    const TABLE_NAME = 'Person';

	    /**
	     * The state of the person (account status).
	     *
	     * @var \Aplha\Model\Type\Enum
	     *
	     * @since 1.0
	     */
	    protected $state;

		// ...

	    /**
	     * Constructor for the class that populates all of the complex types with default values.
	     *
	     * @since 1.0
	     */
	    public function __construct()
	    {
	        // ...

	        $this->username = new SmallText();
	        $this->username->setRule(Validator::REQUIRED_USERNAME);
	        $this->username->setSize(70);
	        $this->username->setHelper('Please provide a name for display on the website (only letters, numbers, and .-_ characters are allowed!).');

	        $this->email = new SmallText();
	        $this->email->setRule(Validator::REQUIRED_EMAIL);
	        $this->email->setSize(70);
	        $this->email->setHelper('Please provide a valid e-mail address as your username.');

	        $this->password = new SmallText();
	        $this->password->setSize(70);
	        $this->password->setHelper('Please provide a password for logging in.');
	        $this->password->isPassword(true);

	        $this->state = new Enum(array('Active', 'Disabled'));
	        $this->state->setValue('Active');

	        // ...
	    }

	    // ...
	}

As you can see in the example above, each attribute of the _Alpha\Model\Person_ record is defined using a data type in the constructor, along with any additional validation rules, sizes, and helper text to display to the user if the validation rules are broken by their input.  Each attribute will then be mapped to an appropriate column and data type in the database in the _Person_ table, that will be created for you by Alpha.

### ActiveRecord CRUD methods

Once you have an active record defined and the database in place, carrying out typical CRUD operations becomes trivial:

	$record = new Person();
	$record->set('email', '[email protected]');
	$record->save();

	$record->load(25);
	$record->loadByAttribute('email', '[email protected]');
	$records = $record->loadAll(0, 25, 'created_ts'); // load the first 25 Person records sorted by created timestamp
	$records = $record->loadAllByAttribute('state', 'Active', 0, 25, 'created_ts');

	$record->delete();

For a full list of the supported CRUD and table management methods, check the notes in the _Alpha/Model/ActiveRecordProviderInterface_.

### Transaction and error handling

Alpha supports database transactions via a number of static methods on the _ActiveRecord_ class.  Here is a typical example:

	try {
	    ActiveRecord::begin();
	    $cart = new Cart();
	    $cart->load(100);
	    $items = $cart->loadItems();

	    foreach ($items as $item) {
	    	$item->set('amount', $item->get('ammount') - 1);
	    	$item->save();
	    }

	    ActiveRecord::commit();
	} catch (AlphaException $e) {
	    self::$logger->error($e->getMessage());
	    ActiveRecord::rollback();
	    // ...
	}

### Object locking and versioning

Each active record in Alpha maintains a version number that is automatically incremented each time the record is saved.  In order to prevent race conditions when two or more seperate threads attempt to save the same record, a version check is performed pre-save and if the version number being saved is older than the version currently in the database, a _Alpha\Exception\LockingException_ is thrown.  Naturally in your application, you should capture that exception an try to handle it gracefully:

	try {
		$record->save();
	} catch (LockingException $e) {
	    // Reload updated record from the database, display something useful to the user and
	    // then let them try to save the record again...
	}

### History

Alpha can optionally maintain the history of each active record for you, by setting the maintainHistory attribute on the record to true.  Alpha will then create and maintain a second database table for the record type, suffixed with "_history", where it will save a copy of the record each time it is updated.  This means that a full history of changes applied to a record can be maintained indefinetly, if you wish to do so in your application.

	$record = new Person();
	$record->setMaintainHistory(true);
	$record->set('email', '[email protected]');
	$record->save();
	
	$record->set('email', '[email protected]');
	$record->save();
	
	echo $record->getHistoryCount(); // should be 2
	
	// load version 1 of person record 10
	$record->load(10, 1);
	echo $record->get('email'); // [email protected]
	
	// load version 2 of person record 10
	$record->load(10, 2);
	echo $record->get('email'); // [email protected]

Controllers
-----------

### ControllerInterface

All controllers in Alpha should inherit from the _Controller_ abstract class and implement the _ControllerInterface_.  The interface defines all of the methods that handle a HTTP request, and includes a method for each of the HTTP verbs (doGET, doPOST, doPUT etc.).  Each of these methods accept a _Request_ object as the only parameter, and return a _Response_ object.  Here is a simple example:

	

	namespace My\App\Controller;

	use Alpha\Controller\Controller;
	use Alpha\Controller\ControllerInterface;
	use Alpha\Util\Http\Request;
	use Alpha\Util\Http\Response;

	class HelloController extends Controller implements ControllerInterface
	{
		public function doGET($request): \Alpha\Util\Http\Response
		{
			$name = $request->getParam('name');

			return new Response(200, 'Hello '.$name, array('Content-Type' => 'text/plain'));
		}
	}

### Routing

Routing a HTTP request to the correct controller is handled by the _FrontController_.  There are two ways to route a request: using a user-friendly URL, or using a secure URL containing an encrypted token that holds the params and controller name for the request.

#### User-friendly URL

In your _index.php_ bootstrap file, you should instantiate a new _FrontController_ to handle all requests.  Routes can then be added to the FrontController like so:

	use Alpha\Controller\Front\FrontController;
	use My\App\Controller\HelloController;

	// ...

	$front = new FrontController();

	$this->addRoute('/hello/{name}', function ($request) {
        $controller = new HelloController();

        return $controller->process($request);
    });

    $request = new Request(); // this will build the request from super global data.
	$response = $front->process($request); // this will map the requested route to the correct controller
	echo $response->send(); // send the response to the client

The _FrontController::process()_ method will take care to map the requested route to the correct controller, while the _Controller::process()_ method called within the addRoute closure will map the HTTP request verb (e.g. GET) to the correct controller method (e.g. doGET).

Note that you can also define default request parameters in the route, effectively making them optional:

	$this->addRoute('/hello/{name}', function ($request) {
        $controller = new HelloController();

        return $controller->process($request);
    })->value('name', 'unknown'); // if the client requests /hello, return "hello unknown"

#### Secure token URL

If you are concerned about passing sensitive information via the query string or as a route parameter, you can generate a secure URL for the controller like so:

	$url = FrontController::generateSecureURL('act=My\App\Controller\HelloController&name=bob');
	// $url now something like "http://www.myapp.com/tk/gKwbKqR7uQq-d07z2y8Nnm1JnW_ZTKIUpT-KUJ7pYHxMouGoosktcIUiLKFz4uR8"

Note that the URL generate will be automatically unencoded and decrypted by the FrontController when requested, using the secret encryption key set in your config file during installation.

Views
-----

Views in Alpha are made up of two parts: _view classes_ that are responsible for marshalling active records to views, and _view templates_ that are responsible for defining the actual view content.

### View classes

A view class should extend the _Alpha\View\View_ class, that defines standard set of methods that are available to a view (createView(), editView(), listView() etc.).  You can then override these methods in case you need to do something specific in your view.  Typically, there is a one-to-one mapping between a view and the corresponding active record that it is rendering, and the view is responsible for marshalling the record data to an underlying template.

Here is an example where we are injecting in a count of the items in a given shopping cart, to be used later on in the template to display cart details:

	

	use Alpha\View\View;
	use My\App\Model\Cart;
	use My\App\Model\Item;
	// ...

	class CartView extends View
	{
	    // ...

	    public function detailedView($fields = array()): string
	    {
	        // this->record will be set to our cart at this stage during factory instantiation
	        $items = $this->record->getItems();

	        $fields['itemCount'] = count($items);

	        // ...

	        $html = $this->loadTemplate($this->record, 'detail', $fields);

	        return $html;
	    }
	}

### View templates

While you can generate HTML directly in your view class methods and return that, typcially you will want to maintain your HTML in a template where it is easier to manage.  The _View_ class provides two seperate methods for loading a template:

	// Assuming that this->record is a My\App\Model\Cart instance, this will check in the following locations for the template:
	// 1. [app.root]/View/Html/Templates/Cart/detail.phtml (this is where you should place your custom templates)
	// 2. [app.root]/Alpha/View/Renderer/Html/Templates/Cart/detail.phtml
	$html = $this->loadTemplate($this->record, 'detail', $fields);

	// You can also load a fragment template (does not