PHPEasy is an API-centric PHP framework. Code as close to PHP language itself rather than a framework.
I. Intro
II. Pre-requisites
III. Installation
This is for someone who loves Vanilla PHP and its simplicity. Nowadays you must follow coding standards(OOP,SOLID,DRY,etc.) and mvc frameworks to do web development using PHP. PHP frameworks out there comes with too much files, configurations, classes and dependencies. I made this mini framework so php developers can do web development faster while mastering and enjoying the PHP language itself (Yes! no need to learn so many libraries).
Composer - open a terminal inside your root or htdocs folder and execute the command below.
composer create-project vgalvoso/phpeasy my_phpeasy
you can change [my_phpeasy] to any project name you want.
Now open your browser and go to http://localhost/my_phpeasy
Create views inside View folder.
View routes will be automatically created based on View folder structure.
Look at examples below.
You can ommit the file name if the view file is named [index.php]:
(SPA)Single Page Applications are composed of view components.
View components are accessible only through ajax requests.
Just call Core/Helper/component(); at the top of view file to specify it as a view component.
Example: View/admin/users_table.php
<?= Core/Helper/component(); ?>
<table>
<thead>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody id="users_tbl">
<tr><td>No Contents</td></tr>
</tbody>
</table>PHPEasy supports REST API.
All APIs are placed inside api folder.
API routes will automaticaly created through api folder file structure and implemented functions inside the php file named with http verbs e.g.(get(),post(),patch()).
So for example you omitted the delete() function, you can't call DELETE api/users/{id}.
Here is an example of a Users REST API.
API file path: [api/users.php]
Routes:
<?php
use CoreDAL;
use function CoreHelpererror;
use function CoreHelpergetRequestBody;
use function CoreHelperresponse;
use function CoreHelperstartAPI;
startAPI();
function get(){
$db = new DAL();
//GET user by id
if(defined('URI_PARAM')){
$query = "SELECT * FROM users WHERE id = :id";
$param = ["id" => URI_PARAM];
if(!$user = $db->getItem($query,$param))
response([]);
response([$user]);
}
//GET All users
$query = "SELECT * FROM users";
$users = $db->getItems($query);
response($users);
}
function post(){
$db = new DAL();
$rq = (object)getRequestBody();
$values = [
"username" => $rq->username,
"firstname" => $rq->firstname,
"lastname" => $rq->lastname,
"usertype" => $rq->usertype,
"password" => password_hash($rq->password,PASSWORD_BCRYPT)
];
if(!$db->insert("users",$values))
error($db->getError());
response("New User added!");
}
function delete(){
if(!defined('URI_PARAM'))
error("Invalid Request! Please specify user id");
$db = new DAL();
$id = URI_PARAM;
if(!$db->delete("users","id=:id",["id" => $id]))
error($db->getError());
response("User Deleted Successfuly!");
}
function patch(){
if(!defined('URI_PARAM'))
error("Invalid Request! Please specify user id");
$db = new DAL();
$id = URI_PARAM;
$rq = (object)getRequestBody();
$values = [
"firstname" => $rq->firstname,
"lastname" => $rq->lastname];
$params = ["id" => $id];
$db = new DAL();
if(!$db->update("users","id=:id",$values,$params))
error($db->getError());
response("User Updated Successfuly");
}
//EOFAPIs in PHPEasy encourages a procedural coding style,
so here are the list of functions that you can use in API implementations:
Initialize a PHP file as a REST API.
After calling this function you can implement http verbs as function.
Example:
<?php
use function CoreHelperstartAPI;
startAPI();
function get(){
//Handle GET request to api/users
}Error response will be received if you try to request using http methods other than GET.
Get request body and convert it into assoc array.
Example:
<?php
use CoreHelpergetRequestBody;
$rq = getRequestBody();
$username = $rq["username"];
$password = $rq["password"];
//you can convert it to object for easy access
//$rq = (object)$rq;
//$username = $rq->username;
//$password = $rq->password;Validate a key-value pair array based on validation rules.
$inputs - Associative array to be validated.$validations - Associative array containing keys that matched keys in $data and values are the validation rules.Example:
<?php
use function CoreHelpergetRequestBody;
use function CoreValidatorvalidate;
$rq = getRequestBody();
$dataRules = ["uname" => "required|string",
"upass" => "required|string",
"firstName" => "required|string",
"lastName" => "required|string"];
validate($rq,$dataRules);Output response with 400 status code and error message
$message - String|Array Error MessageSet content type and status code then output content and exit script
$content string|array - The content to output$statusCode int - The response status code (default 200)$contentType string - The content type (default application/json).
Available content-types: [ application/json | plain/text | text/html ]Include specified view
$route string - View file pathMostly used for calling SPA component
Redirect to specified view.
If path is not specified, redirect based on session.
$view string - Path to viewShorter syntax for htmlspecialchars()
$string - String to sanitizeGenerate a randomized alphanumeric code
$length - Length of code to be generated (default 6)Extract object keys and values and store to session array
$object - The object to extract
Example:<?php
use CoreDAL;
$db = new DAL();
if(!$user = $db->getItem(1))
invalid("User does not exist!");
objToSession($userInfo);Generate new file name and upload the file
string $uploadFile $_FILE keystring $uploadPath Location for upload file must add "/" to the endGet/Set a session variable
$sessionVar - Session Key$value - Sets a session value if nullConvert an array of objects to indexed array containing values of specified item.
$objArr - Array if ibjects to convert$item - object item to extractPHPEasy introduces DAL() class for database operations. Supports MYSql, MSSql and SQLite.
Set database configurations in Config/Database.php
Below are DAL() functions
$db = new DAL();Executes an INSERT statement;
$table - The table name to be inserted$values - Associative array containing keys that match table fields and the values to insert.Example:
$values = ["username" => $uname,
"password" => $upass,
"firstname" => $firstName,
"lastname" => $lastName];
$db->insert("users",$values);Executes update statement
string $table The table to updatestring $condition Conditions eg. id = :idarray $values Associative array containing values to update eg .["age" => 27]array $params Values for conditions eg . ["id" => 1]Example:
$values = [
"firstname" => $firstName,
"lastname" => $lastName];
$params = ["id" => 1];
$db = new DAL();
$db->update("users","id=:id",$values,$params);Executes delete statement
string $table The table to delete fromstring $condition Conditions using prepared statement eg. id = :id AND name = :namearray $params Values for conditions eg. ["id" => 1,"name" => "Juan Dela Cruz"]Example:
$delete("users","id=:id",["id" => 1]);Select multiple items
string $query Select statementarray $inputs Parameters for prepared statement default(null)Example:
$db = new DAL();
$sql = "SELECT * FROM users WHERE lastname = :surname";
$params = ["surname" => $lastName];
$users = $db->getItems($sql,$params);Select single row query
string $query Select statementarray $inputs Parameters for prepared statement default(null)Example:
$db = new DAL();
$sql = "SELECT * FROM users WHERE id=:userId";
$params = ["userId" => 1];
$users = $db->getItem($sql,$params);Start a database transaction.
Commit database transaction.
Rollback database transaction.
Returns Database Errors
Get lastId inserted to database
string $field Specify a lastId field, default nullGet the database friver that is currently used.
- api/getAllUser.php
```php
<?php
$db = new DAL();
$users = new Users($db);
$usersList = $users->getAll();
You can use models or not depending on project requirements.
DAL class is accessible directly in api files, you can execute a query directly on api implementation without creating a Model.
PHPEasy is progressive, you can add Models, Services if you like, just update the composer.json file if you added other directory.
See