Download the PHP package natecollins/nofus without Composer
On this page you can find all versions of the php package natecollins/nofus. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download natecollins/nofus
More information about natecollins/nofus
Files in natecollins/nofus
Package nofus
Short Description Nate's One-File Utilities Stash: Simple Single-use Classes for Common Tasks
License BSD-2-Clause
Informations about the package nofus
NOFUS: Nate's One-File Utilities Stash
About NOFUS
A collection of single purpose classes for common tasks, focusing on simple and straightforward use. Each class can be taken and used individually and requires no external code dependencies.
Classes
- ConfigFile.php - Easy parser for config files
- Logger.php - Simple logger class with built-in file logging implementation
- DBConnect.php - Quick, safe interface for making MySQL/MariaDB queries
- UserData.php - Simple validator for user data
Installation
The recommended method of installation is to use Composer. However, if all you need is a specific file, it can be downloaded independently and will work without any of the other files present.
To install via composer:
ConfigFile.php
A class to read in plain text config files.
- Simple "variable = value" syntax
- Allows quoted string values
- Allows line comments, including end line
- Allows variable scopes
- Allows scope section definitions
- Allows valueless variables
- Allows multiple values per variable name
- Can enumerate available scopes
- Can preload default values
Sample Config File:
Examples:
Loading only loads the first time
Calling the load()
method only parses and loads the config file the first time for any ConfigFile
object. Subsequent calls check if the file was successfully loaded the first time, and then doesn't
bother to re-parse.
If you want to force a config file to re-load a file, you must first reset()
the ConfigFile object
and then load()
it again. Note that this will also clear out any preload()
variables, so you will
have to preload()
them again after calling reset()
.
Logger.php
A class to create logs, with a built-in simple file-logging implementation
- Very simple to setup and use
- Can register custom logger implementations to replace built-in file-logger
- Can specify log levels
Examples:
DBConnect.php
A class to handle MySQL/MariaDB compatible database connections. Features include:
- Automatic failover between multiple servers
- Safe escaping of data via prepared statements
- Based off PDO extension
- Query tracking
- Query construction emulation (for debugging)
- Safe escaping of user supplied table and column names
- Single SQL connection shared among all instances
Required Libraries
- PDO
- MySQL
On Ubuntu, this can be installed via:
Establishing a Connection
Establishing a connection to SQL server requires an array object to be passed. This array must
contain at least one set of server authentication parameters, including host
, username
,
password
, and database
. More than one set of parameters can be passed if you have redundant
SQL servers, in which case each server will be tried in-order until a connection is established
or there are no connection left to try.
Pass the array of connection parameters to the DBConnect
object to prepare your connection.
Executing Queries
To execute a query, you pass a query string and an array of values to the query()
method.
If there are no values, you can omit the second argument. All queries are processed as
prepared queries.
Return values are dependent on the type of query that is run. SELECT
queries return an array
of rows; INSERT
queries return the unique id of the new row or null
otherwise; DELETE
and UPDATE
queries return the number of rows affected.
Additional means of running queries include:
queryRow
Only the first row of results is returned. If no rows are found, returns null.queryColumn
Returns an array containing the values of a specific column. By default, the first column is used.queryLoop
&queryNext
For gathering results one row at a time. See examples below.queryPrepare
For manually creating a prepared query, with the ability to re-use it multiple times.
Example Queries:
Showing Errors and Debug Information
By default, an uninformative message is thrown on Exceptions. To enable automatic display of detailed errors
and output of query information during development, make sure you enable debugging information:
To enabled detailed exception messages, but disable auto-dumping query error information to the output stream:
Alternatively, you can manually retrieve the error information after catching the Exception:
Throwing Exceptions
The silentErrors()
method will set the PDO::ATTR_ERRMODE
. By default, PDO exceptions
will be thrown.
Setting PDO Attributes Manually
You can always set PDO Attributes maually with the setPDOAttribute()
method. This takes a PDO constant
and an appropriate value and sets the attribute when creating a connection. If an attribute is set to null
,
then that previously set attribute is removed and will not be set. If a database connection had previously been
established, calling this method will disconnect it, forcing a new connection with the updated attribute when
the next query is called.
Sanitizing Identifiers
Table and column names are not typically something you want to use variables for, but there are rare circumstances
where it might be needed. By calling escapeIdentifier()
, you can ensure your identifer is sanitized and safe from
SQL injection attacks. This is accomplished by querying the database for all valid table and column names, and only
if the passed identifier exactly matches an existing database identifier pulled from the database is it considered
safe. If the identifer is not safe, an empty string is returned.
NOTE: This only checks that the identifier is valid in the database. You should still never trust user supplied data for use in your queries.
For performance reasons, this method only queries the database for identifiers the first time it is called. The method caches the results and any subsequent calls make use of the data previously loaded.
An optional second boolean parameter can be passed if you want to specify that the resulting identifier should not be backtick quoted.
Load Balancing Multiple Servers
Not a true load balancer yet, the loadBalance()
method will shuffle the order in which servers are connected to.
Obviously, this must be called before any queries are run and any connections are established.
Forcing a Connection to End
You can force a connection to a database to end by calling the close()
method. This method does
nothing if the connection is already closed.
Get Database Hostname
Get Database Name
Returns the name of the database currently connected. If no database is connected, will attempt to
connect to one and return it. If it cannot connect to any databases, it will return an empty string.
Debugging a Query
To dump the PDO debugParams and get a copy of the query string for the last query run, you can call
the getLast()
method. If you ran series of querys as a transaction, then it will include all queries
that were part of that transaction.
To emulate a query before it's run and see what it will likely be combined as, you can call either
the queryReturn()
or queryDump()
methods. The first of which emulates joining the query and values
together and returns it as a string; the latter which does the same, but dumps the query to stdout.
Grabbing a List of Enum Values
If a table column is an enum, you can get and array containing all possible
enum values by calling the enumValues()
method, and passing the table
and column in question. The returned array will be ordered in the same order
as the enum values are defined in the table.
Using Transactions
Transactions can be used via the methods startTransaction()
, commitTransaction()
, and rollbackTransaction()
assuming the database engine support it.
By default, MySQL sets the transaction isolation to REPEATABLE READ
. You can change this to READ COMMITTED
by passing
a boolean true
when starting the transaction.
Get Count of Query Calls Made
To get a listing of the total number of queries for this specific instance of
a DBConnect object, you can use the getQueryCount()
method.
UserData.php
A class to access and validate user data types from GET, POST, COOKIE, and FILES.
- Object based interface
- Support for retrieving arrays of values, including file data
- Functions auto-convert to basic data types
- Simple filter options for range, length, regexp, or pre-set values
- Default value option for all value retrieval functions
Creating UserData Objects
When creating a new UserData object, you must specify the name of the data field to retrieve, and
optionally name where to look for the data at. If not specified, UserData will look for the
value field in-order from these locations: GET, POST, COOKIE, and FILES.
Getting Simple Values
Getting simple values is easy, and returns the appropriate value type,
or returns null if variable name was not passed.
Setting Default Values
If no value was found, use the default value passed instead. With
out a default value specified, the default is null.
Filter by Allowed Values
If you know the value retrived must be from a set of values, you can
set a filter to reject all but those values. Any non-allowed values
will return the default value instead.
Filter by Range
Only applicable when getting integer or float values. Values outside
the range will return the default value, unless set to limit the value.
Filter by Length
Only applicable for string values. Values not within length limits
will return the default value, unless set to truncate.
Filter by Regular Expression
Only applicable for string values. Values not matching pattern
will return the default value.
Checking if Field with Name Exists
To check if a field with a given name exists, even if the value passed
was blank.
Get Errors
If your value is out of bounds of a filter, it will generate an error
message. All error messages are stored in an array. Using getErrors()
you can retrieve and view those filter errors.
Get File Values
Get information about an uploaded file. Returns array containing:
name
The original name of the uploaded filetype
The mime type of the file (can be falsified by client)size
The size of the uploaded filetmp_name
The file location and name as it exists on the servererror
An error code if there was a problem with the upload (0 means no error)
Get Array Values
When using PHP form variable arrays, you can use the array version of
the UserData functions. Any filters you've applied will apply to each
value of the array.