PHP code example of firelit / framework

1. Go to this page and download the library: Download firelit/framework 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/ */

    

firelit / framework example snippets




// Setup
$resp = Firelit\Response::init();
$reqs = Firelit\Request::init();
$router = Firelit\Router::init($reqs);

$router->add('GET', '!^/Hello$!', function() {
	// Simple route, you'd go to http://example.com/Hello and get this:
    echo 'World!';
});

$router->add('GET', '!^/redirect$!', function() use ($resp) {
	// Redirect example
    $resp->redirect('/to/here');
});

$router->add('POST', '!^/forms!', function() {
    // Process the POST request in a controller
    Firelit\Controller::handoff('Controller\Forms', 'process');
});

$router->add('GET', '!^/groups/([^0-9]+)$!', function($matches) {
	// Match URL parts with regular expressions to extract information
	echo 'You selected group #'. $matches[0];
});

// You can nest routes to keep things organized
$myNestedRoutes = 



$resp = Firelit\ApiResponse::init('JSON');

$resp->setTemplate(array(
	'success' => false,
	'message' => ''
));

$resp->code(404);

$resp->respondAndEnd(array(
	'message' => 'Resource could not be located.'
));



Firelit\Cache::config(array(
	'memcached' => array(
		'enabled' => true,
		'servers' => array(
			array(
				'host' => 'localhost',
				'port' => 11211,
				'persistent' => true,
				'weight' => 1,
				'timeout' => 1
			)
			/* Multiple servers can be added */
		)
	)
));

$val = Firelit\Cache::get('randomValue', function() {

	// If cache miss, this closure will execute this closure, storing the returned value in cache
	return mt_rand(0, 1000);

});

if (Firelit\Cache::$cacheHit)
	echo 'Cache hit!';

// Set a value to null in order to remove it from cache
Firelit\Cache::set('randomValue', null);



class DashboardController extends Firelit\Controller
{

	public function show($userName)
	{
		// This skelton controller method retrieves a view template, populates and renders
		$data = GetMyData::now();

		Firelit\View::quickRender('DashboardView', 'LoggedinLayout', array('name' => $userName));
	}

}

// You could invoke this as you would any class, but the handoff method makes it a one-liner:
Firelit\Controller::handoff('DashboardController', 'show', $userName);



$mySecret = 'Super secret!';

// Private key encryption
$key = Firelit\CryptoKey::newPrivateKey(); // Can be 1024, 2048 or 3072-bit
$crypto = new Firelit\Crypto($key);

$ciphertext = $crypto->encrypt($mySecret)->with(Firelit\Crypto::PUBLIC_KEY);

$plaintext = $crypto->decrypt($ciphertext)->with(Firelit\Crypto::PRIVATE_KEY);

// Symmetric key encryption
$key = Firelit\CryptoKey::newSymmetricKey(); // Can be 128, 192 or 256-bit
$crypto = new Firelit\Crypto($key);

$ciphertext = $crypto->encrypt($mySecret);

$plaintext = $crypto->decrypt($ciphertext);

// Robust, mixed-type private key encryption
$key = Firelit\CryptoKey::newPrivateKey(); // Can be 1024, 2048 or 3072-bit
$crypto = new Firelit\CryptoPackage($key);

$object = (object) array(
	'test' => true,
	'string' => $mySecret . $mySecret . $mySecret
);

$ciphertext = $crypto->encrypt($object)->with(Firelit\Crypto::PUBLIC_KEY);

$objectBack = $crypto->decrypt($ciphertext)->with(Firelit\Crypto::PRIVATE_KEY);



class Person extends Firelit\DatabaseObject
{

    protected static $tableName = 'People'; // The table name
    protected static $primaryKey = 'id'; // The primary key for table (array for multiple keys, false if n/a)

    // Columns that should be automatically php-serialized when using
    protected static $colsSerialize = array('nicknames');
    // Columns that should be automatically JSON-encoded/decoded when using
    protected static $colsJson = array();
    // Columns that should be a DateTime object when loaded from DB
    protected static $colsDateTime = array('created');

}

// Create a new person
$newPerson = Person::create(array(
	'name' => 'Sally',
	'email' => '[email protected]',
	'nicknames' => array('Sal'),
	'created' => new DateTime()
));

// Find by the primary key
$person = Person::find(23);

// Returns FALSE if not found
if (!$person) die('Not found');

// Serialized columns are serialized before being saved and unserialized on retrieval
$person->nicknames = array(
	'Bill',
	'Will',
	'William'
);

// Easily save to database (uses primary key set during retrieval)
$person->save();

// Or find rows by other columns
$persons = Person::findBy('email', '[email protected]');

// DatabaseObject::findBy returns an iterable object (Firelit\QueryIterator) for search results
foreach ($persons as $person) {
	// DateTime columns are converted to DateTime objects on retrieval
	echo $person->name .' was created '. $person->created->format('n/j/y') . PHP_EOL;
}




Firelit\HttpRequest::config(array(
	'userAgent' => 'My little user agent string'
));

$http = new Firelit\HttpRequest();

$http->enableCookies();

// 'get', 'post' and 'other' (for put, delete, etc) are also available methods
$http->get('http://www.google.com/');

// Hmmm, I wonder what cookies Google sets...
echo '<pre>'. file_get_contents($http->cookieFile) .'</pre>';



// One-time connection setup
Firelit\Registry::set('database', array(
	'type' => 'mysql',
	'name' => 'database',
	'host' => 'localhost', // Hostname or IP acceptable here
	'port' => '3306', // Can be left undefined to use default port
	'user' => 'username',
	'pass' => 'password'
));

// Or specify the DSN string for PDO to connect to other types of databases
Firelit\Registry::set('database', array(
	'type' => 'other',
	'dsn' => 'sqlite::memory:'
));

/* 
Alternatively, database settings can be specified using the following environmental variables:
 - DB_NAME
 - DB_HOST
 - DB_PORT
 - DB_USER
 - DB_PASS
*/

$q = new Firelit\Query();

$q->insert('TableName', array(
	/* columnName => value */
	'name' => $name,
	'state' => $state
));

if (!$q->success()) die('It did not work :(');

$q->query("SELECT * FROM `TableName` WHERE `name`=:name", array('name' => $name));

while ($row = $q->getRow())
	echo $row['name'] .': '. $row['state'] .'<br>';



function demo($type)
{

	$q = new Firelit\Query();

	$q->query("SELECT * FROM `TableName` WHERE `type`=:type", array('type' => $type));

	return new Firelit\QueryIterator($q);

}

$results = demo('best_ones');

foreach ($results as $index => $value) {
	// Do something!
}




$req = new Firelit\Request::init( function(&$val) {

	// Remove any invalid UTF-8 characters from $_POST, $_GET and $_COOKIE
	Firelit\Strings::cleanUTF8($val);

});

// Filtered $_POST, $_GET and $_COOKIE parameters can then be accessed via the object
if ($req->get['page'] == '2') showPageTwo();


// Handle JSON body parsing and PUT requests automatically
$req = new Firelit\Request::init(false, 'json');

// Filtered $_POST, $_GET and $_COOKIE parameters can then be accessed via the object
$newName = $req->put['name'];



$sess = new Firelit\Session::init(new Firelit\DatabaseSessionHandler);

$sess->loggedIn = true;
$sess->userName = 'Peter';

echo '<p>Hello '. htmlentities($sess->userName) .'</p>';


// Check if an email is valid
$valid = Firelit\Strings::validEmail('[email protected]'); // $valid == true

// Clean the strings in the array for all valid UTF8
Firelit\Strings::cleanUTF8($_POST); // The parameter is passed by reference and directly filtered

// Normalize the formatting on a name or address
$out = Firelit\Strings::nameFix('JOHN P.  DePrez SR'); // $out == 'John P. DePrez Sr.'
$out = Firelit\Strings::addressFix('po box 3484'); // $out == 'PO Box 3484'

// Multi-byte HTML and XML escaping
$out = Firelit\Strings::html('You & I Rock'); // $out == 'You &amp; I Rock'
$out = Firelit\Strings::xml('You & I Rock'); // $out == 'You &#38; I Rock'

// Format the string as a CSV cell value (escaping quotes with a second quote)
$out = Firelit\Strings::csv('John "Hairy" Smith'); // $out == '"John ""Hairy"" Smith"'

// Multi-byte safe string case maniuplation
$out = Firelit\Strings::upper('this started lower'); // $out == 'THIS STARTED LOWER'
$out = Firelit\Strings::lower('THIS STARTED UPPER'); // $out == 'this started upper'
$out = Firelit\Strings::title('this STARTED mixed'); // $out == 'This Started Mixed'
$out = Firelit\Strings::ucwords('this STARTED mixed'); // $out == 'This STARTED Mixed'



// Configuration
new Firelit\Vars::init(array(
	'table' => 'Vars',
	'col_name' => 'Name',
	'col_value' => 'Value'
));

// Later usage
$vars = new Firelit\Vars::init();

// Set a persistent application variable with any name accepted by your store
$vars->maintenanceMode = true;

// Read a persistent application variable
if ($vars->maintenanceMode) die('Sorry, under construction.');

 if (!is_object($this)) die; 

 if (!is_object($this)) die; 


// The view folder can be changed with a static property. The php extension is added if not supplied.
$view = new Firelit\View('templates\dashboard', 'layouts\main');

// Here the view is sent to the client
// The data to be available in the view is given as an array
$view->render(array('name' => 'John'));

php composer.phar