PHP code example of natecollins / nofus

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

    

natecollins / nofus example snippets


use Nofus\ConfigFile;

# Create config file object and attempt to load it
$cf = new ConfigFile('app.conf');

if (!$cf->load()) {
    echo "Could not load file!" . PHP_EOL;
    print_r( $cf->errors() ); // an array of reasons for failure to load
    exit(1);
}

####################################################
# Optionally preload default values (will NOT override already loaded values)
$cf->preload(
    array(
        "email"=>"root@localhost",
        "debug_mode"=>false,
        "address.home.city"=>"Kalamazoo",
        "address.home.state"=>"Michigan"
    )
);

####################################################
# Simple Variable
$email = $cf->get('email');
// if the email variable exists in the file, returns it as a string; if not, returns null

####################################################
# Simple Variable with Default Value
$phone = $cf->get('phone', '555-1234');
// if the phone variable exists in the file, returns it as a string; if not, returns '555-1234'

####################################################
# Simple Valueless Variable
$debug = $cf->get('debug_mode', false);
// valueless variables return true if they exist, otherwise returns the custom default of false

####################################################
# Get Quoted Value
$nickname = $cf->get('nickname');
echo "==${$nickname}==";
# will print: == John "Slick" Doe ==

####################################################
# Get Variable with Scope
$birthdate = $cf->get('date.birth');

####################################################
# Get Scope, Example 1
$home = $cf->get('address.home');
$home_line_1 = $home->get("line_1");

####################################################
# Get Scope, Example 2
$addresses = $cf->get('address');
$work_line_1 = $addresses->get("work.line_1");

####################################################
# Get Array of Values
$first_child = $cf->get("children.name");
$children = $cf->getArray("children.name");
// value of $first_child would be the string 'Alice'
// value of $children would be the array: ('Alice','Bobby','Chris')

####################################################
# Enumerate available scopes
$scopes1 = $cf->emumerateScope("address.work");
$scopes2 = $cf->emumerateScope();   // Default enumerates top level scope
// value of $scopes1 would be the array: ('line_1','line_2','state','city')
// value of $scipes2 would be the array: ('email','name','debug_mode','nickname','date','address','children')

$cf->reset();
$cf->load();

use Nofus\Logger;

# Initialize logger with built-in file logger; default level logs all levels
Logger::initialize('/path/to/file.log')

# Initialize logger with customize logger levels
Logger::initialize('/path/to/file.log', Logger::LOG_ERROR | Logger::LOG_CRITICAL);

# Disable logger
Logger::disable();

# Register custom logger instance which must implement `LoggingInterface`.
Logger::register( new CustomLogger() );

# Make log entries
Logger::debug("Debug!");
Logger::notice("Notice!");
Logger::warning("Warning!");
Logger::error("Error!");
Logger::critical("Critical!");

# Log entry which 

use Nofus\DBConnect;

$sql_servers = array(
    array(
        'host'=>'primarymysql.example.com',
        'username'=>'my_user',
        'password'=>'my_pw',
        'database'=>'my_db'
    ),
    array(
        'host'=>'secondarymysql.example.com',
        'username'=>'my_user',
        'password'=>'my_pw',
        'database'=>'my_db'
    )
);

$db = new DBConnect($sql_servers);

####################################################
# Simple Query
$query = "SELECT firstname, lastname FROM users WHERE age > ? AND lastname != ?";
$values = array(21, "Smith");

$names = $db->query($query, $values);

foreach ($names as $row) {
    echo "{$row['lastname']}, {$row['firstname']}";
}

####################################################
# Labeled Placeholders
$query = "SELECT firstname, lastname FROM users WHERE hair_color = :hair";
$values = array(":hair"=>"brown");

$names = $db->query($query, $values);

####################################################
# Single Row Query
$query = "SELECT firstname, lastname FROM users WHERE user_id = ?";
$values = array(42);

$row = $db->queryRow($query, $values);

if ($row !== null) {
    echo "{$row['lastname']}, {$row['firstname']}";
}

####################################################
# Argument Expansion Query (tabase column

####################################################
# Loop Over Large Resultset Query
$query = "SELECT firstname, lastname FROM phone_directory WHERE country = ?";
$values = array('US');

$db->queryLoop($query, $values);
while ($row = $db->queryNext()) {
    echo "{$row['lastname']}, {$row['firstname']}";
}

####################################################
# Re-using Prepared Statements (argument expansion not permitted)
$query = "SELECT * FROM users WHERE lastname = ?";
$prepared = $db->prepare($query);

$lastnames = array('Smith','Cooper','Harris');
for ($lastnames as $lname) {
    $users = $db->query($prepared, array($lname));
    echo "Found ".count($users)." users with a lastname of ${lname}";
}

####################################################
# Insert Query
$query = "INSERT INTO users (firstname, lastname) VALUES(?,?)";
$values = array('John', 'Doe');

$user_id = $db->query($query, $values);
// returns the last insert id on success, or null on failure

####################################################
# Update Query
$query = "UPDATE users SET lastname = ? WHERE user_id = ?";
$values = array('doe', 42);

$update_count = $db->query($query, $values);
echo "Updated {$update_count} rows.";

####################################################
# Delete Query
$query = "DELETE FROM users WHERE user_id = ?";
$values = array(33);

$delete_count = $db->query($query, $values);
echo "Deleted {$delete_count} rows.";

####################################################
# Safe Table and Column Name Escaping
# (safe from SQL injections; you should still use caution to prevent other shenanigans)
$safe_table = $db->escapeIdentifier($table);
$safe_column = $db->escapeIdentifier($column);
$query = "SELECT firstname, lastname FROM {$safe_table} WHERE {$safe_column} = ?";
$values = array(42);

$names = $db->query($query, $values);

foreach ($names as $row) {
    echo "{$row['lastname']}, {$row['firstname']}";
}


$db->enableDebugInfo();         // See descriptive errors, and dumps error info into output stream

$db->silentErrors();        // disables exceptions on MySQL errors
$db->silentErrors(true);    // also disables exceptions on MySQL errors
$db->silentErrors(false);   // an exception will be thrown on MySQL errors from this connection

$db->setPDOAttribute(PDO::MYSQL_ATTR_COMPRESS, 1);

$column = $obj->getColumnMatch();   // NOT user supplied data

// $safe_column = $db->escapeIdentifier($column);        // by default, result is escaped with backticks
$safe_column    = $db->escapeIdentifier($column, false); // or you can have it not escape with backticks

if ($safe_column == '') {
    echo "Unable to match column!";
    exit(1);
}
$query = "SELECT * FROM books WHERE {$safe_column} = ?";
$values = array( $obj->getColumnValue() );
$results = $db->query($query,$values);

$db->loadBalance();

$db->close();

// prints the domain string used for the 'host' when the current connection was created
$db->getHost();
// if no connection exists or if the connection was closed, empty string will be returned
$db->close(); 
$db->getHost(); // returns ''

$db->getDatabaseName();

$db->getLast()

$debug = $db->queryReturn($query,$values);
$db->queryDump($query,$values);

$enums = $db->enumValues('mytable', 'mycolumn');

$db->startTransaction();

$update_count = $db->query($query, $values);
if ($update_count > 1) {
    $db->rollbackTransaction();
}
else {
    $db->commitTransaction();
}

$db->startTransaction(true);

$count = $db->getQueryCount();

use Nofus\UserData;

# Create UserData objects 
$ud_userid = new UserData("user_id");
$ud_message = new UserData("message", "POST");

# Alternate way of creating UserData objects
$ud_attachments = UserData::create("attach", "FILES");
$ud_session = UserData::create("sess_key", "COOKIE");

# Get string values
$firstname = $ud_firstname->getStr();
$lastname = $ud_lastname->getString();

# Get integer values (truncates decimals)
$age = $ud_age->getInt();
$zip = $ud_zipcode->getInteger();

# Get float values
$temperature = $ud_temp->getFloat();
$distance = $ud_dist->getDouble();

# Get boolean values (true values are either: 1, true)
$allow_email = $ud_email->getBool();
$allow_text = $ud_text->getBoolean();

$msg_type = $ud_type->getStr("public");
$guest = $ud_guest->getBoolean("1");

$ud_acct->filterAllowed( ['guest','normal','admin'] );
$acct_type = $ud_acct->getStr("guest");

$ud_age->filterRange(0,120);
$age = $ud_age->getInteger();

# Only limit the minimum 
$ud_minimum->filterRange(15.0);

# Only limit the maximum range
$ud_maximum->filterRange(null, 99.5);

# Limit the value to be within the filter range
$ud_limit->filterRange(0, 100, true);

# Filter minimum and maximum length
$ud_username->filterLength(2, 10);

# Filter minimum length only
$ud_username->filterLength(2);

# Filter minimum length and truncate string past maximum length
$ud_username->filterLength(2, 10, true);

$ud_date->filterRegExp('/^\d{4}-\d\d-\d\d$/');

$ud_check = UserData::create('check');
if ($ud_check->exists()) {
    echo "Field with name 'check' was submitted.";
}
else {
    echo "Field 'check' was not sent to us.";
}

$errors = $ud_data->getErrors();
foreach ($errors as $err) {
    echo "$err";
}

$file_info = $ud_attachment->getFile();

$string_array = $ud_list->getStrArray();
# Can still provide default value to return
$string_array = $ud_list->getStringArray( array() );

$int_array = $ud_numbers->getIntArray();
$int_array = $ud_numbers->getIntegerArray();

$float_array = $ud_numbers->getFloatArray();
$float_array = $ud_numbers->getDoubleArray();

$bool_array = $ud_switches->getBoolArray();
$bool_array = $ud_switches->getBooleanArray();

$file_array = $ud_files->getFileArray();

apt install php-pdo-mysql

echo $db->getErrorInfo();       // Manually get error info