All Projects → nicollassilva → SimplePHP

nicollassilva / SimplePHP

Licence: MIT license
A small query builder project designed to assist daily routines and speed up the process of communicating with the database.

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to SimplePHP

mern-stack-crud
MERN stack (MongoDB, Express, React and Node.js) create read update and delete (CRUD) web application example
Stars: ✭ 142 (+914.29%)
Mutual labels:  crud, read, update, create, delete
crud-app
❄️ A simple and beautiful CRUD application built with React.
Stars: ✭ 61 (+335.71%)
Mutual labels:  read, update, create, delete
SQLiteHelper
🗄 This project comes in handy when you want to write a sql statement easily and smarter.
Stars: ✭ 57 (+307.14%)
Mutual labels:  query, update, delete
react-query-builder
Simple, configurable react query builder
Stars: ✭ 37 (+164.29%)
Mutual labels:  query, querybuilder
Graphql To Mongodb
Allows for generic run-time generation of filter types for existing graphql types and parsing client requests to mongodb find queries
Stars: ✭ 261 (+1764.29%)
Mutual labels:  query, update
Dasel
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Stars: ✭ 759 (+5321.43%)
Mutual labels:  query, update
React Query
⚛️ Hooks for fetching, caching and updating asynchronous data in React
Stars: ✭ 24,427 (+174378.57%)
Mutual labels:  query, update
querqy-elasticsearch
Querqy for Elasticsearch
Stars: ✭ 37 (+164.29%)
Mutual labels:  query, querybuilder
aarbac
An Automated Role Based Access Control .NET framework with T-SQL Query Parser which automatically parse select, insert, update, delete queries based on the logged in user role
Stars: ✭ 18 (+28.57%)
Mutual labels:  query, crud
transparencia-dados-abertos-brasil
A survey of Brazilian states' and municipalities' transparency and open data portals, as well as institutional websites, obtained from several public data sources. 🇧🇷 Levantamento de portais estaduais e municipais de transparência e dados abertos, bem como os portais institucionais, obtido a partir de diversas fontes públicas de dados.
Stars: ✭ 46 (+228.57%)
Mutual labels:  transparency
game-executor
采用Reactor模式,注册readycreate, readyfinish事件到更新服务UpdateService,通过处理后进行模型缓存,然后将消息转化为 dispatchThread消息分配模型需要的create, update, finish的事件进行单线程循环调度 。调度过程使用了系统预置锁模型,来进行多线程唤醒机制,将所有的update循环检测进行多 线程调度,多线程更新服务使用future-listener机制,在完成调度后,根据模型状态,如果模型存活重新将消息转化为update 事件注册到dispatchThread消息分配模型进行循环处理。如果模型死亡将消息转化为readyfinish事件注册到更新服务UpdateServic进行销毁 。这个系统实现了模型自动缓存,多…
Stars: ✭ 28 (+100%)
Mutual labels:  update
anapsid
An adaptive query processing engine for SPARQL endpoints.
Stars: ✭ 17 (+21.43%)
Mutual labels:  query
boiler-plate-commands
Package to generate automatic cruds for Laravel BoilerPlate Apps
Stars: ✭ 13 (-7.14%)
Mutual labels:  crud
python-qlient
A fast and modern graphql client designed with simplicity in mind.
Stars: ✭ 29 (+107.14%)
Mutual labels:  query
AdvancedSQL
The best Java query builder/SQL connector.
Stars: ✭ 23 (+64.29%)
Mutual labels:  query
umock-c
A pure C mocking library
Stars: ✭ 29 (+107.14%)
Mutual labels:  easy-to-use
ionic4-angular8-crud-mobileapps-example
Ionic 4 Angular 8 Tutorial: Learn to Build CRUD Mobile Apps
Stars: ✭ 20 (+42.86%)
Mutual labels:  crud
express-mquery
Expose mongoose query API through HTTP request.
Stars: ✭ 37 (+164.29%)
Mutual labels:  query
m-custom-functions
This library contains created mostly pure M-functions without any other languages.
Stars: ✭ 24 (+71.43%)
Mutual labels:  query
minecraft-server-status
PHP library to check Minecraft Servers Status
Stars: ✭ 36 (+157.14%)
Mutual labels:  query

[DESCONTINUED] Simple PHP - Simple and easy CRUD for PHP projects

OBS: This package was replaced by the MinasORM package.

Maintainer Scrutinizer Code Quality PHP from Packagist Software License Latest Version Build Status Code Intelligence Status Total Downloads

Um pequeno projeto CRUD desenvolvido para auxiliar as rotinas diárias e acelerar o processo de comunicação com o banco de dados com segurança e transparência.

A small CRUD project developed to assist daily routines and speed up the process of communicating with the database with security and transparency.

Getting Started

Some precautions and step-by-step instructions for you to download and install the package.

Prerequisites

To be able to use SimplePHP you will need to have:

PHP ^7.2.5
EXT-PDO *

Installing

SimplePHP can be installed via composer.json or via the command terminal:

composer require nicollassilva/simplephp

or composer.json:

"nicollassilva/simplephp": "^1.9"
>>>>>>> Stashed changes

Connection

To configure the connection to the database, you must access: Source\Root\Config.php. Example of the file to be found:

protected $config = [
        "driver" => "mysql",
        "hostname" => "localhost",
        "charset" => "utf8mb4",
        "port" => 3306,
        "username" => "root",
        "password" => "",
        "database" => "",
        "timezone" => "America/Sao_Paulo",
        "pathLog" => __DIR__ . "/../../../../../your-log.log",
        "options" => [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_NATURAL,
            PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
        ]
    ];

Example of your model

After completing the database configuration, create a folder at the root of the project where your Models will be and create the class.

  • You should extend and use the SimplePHP class namespace, as in the example:
namespace Models;

use SimplePHP\Model\SimplePHP;

class User extends SimplePHP {

    function __construct()
    {
        /**
         * @param string Table Name
         * @param string Primary Key
         */
        parent::__construct('users', 'id');
    }
}
  • You will need to inherit your model from the SimplePHP class, and in the magic constructor method, call the parent constructor with the name of the table for the referred model, and a primary key.

First use

After all the previous steps, create an index.php at the root of the project giving a require in the composer autoload and in your model class, after that, instantiate your model and you can start using SimplePHP. Below is an example:

    require "vendor/autoload.php";
    require "models/user.php";

use Models\User;

    $userModel = new User();
    $user = $userModel->find()->execute();

Installation Errors

Some mistakes and how to fix them

Fatal error: Uncaught Error: Class 'SimplePHP\Model\SimplePHP' not found

To fix it, execute the following command in the project's root folder:

composer dump -o

Documentation

Methods

find

use Models\User;

$userModel = new User();

/** find all users */
$user = $userModel->find()->execute();

/** find user by id */
$user = $userModel->find(5)->execute();

/** find users and return the total result count */
$count = $userModel->count()->execute();

/** find user with one where */
$user = $userModel->where([
                                     ['name', '=', 'Nicollas']
                                ])->execute();

/** find user with several where. Conditional AND default */
$user = $userModel->where([
                                     ['name', '=', 'John'],
                                     ['email', '=', '[email protected]']
                                ])->execute();

/** find user with LIKE. Conditional AND default */
$user = $userModel->where([
                                     ['name', 'LIKE', '%Guilherme%'],
                                     ['email', '=', '[email protected]']
                                ])->execute();

/** find user with conditional where. Condicional OR */
$user = $userModel->where([
                                     ['name', 'LIKE', '%Nicollas%'],
                                     ['name', 'LIKE', '%Nicolas%']
                                ], 'OR')->execute();

/** find users by name = Nicollas OR name = Nicolas */
$user = $userModel->where([
				     ['name', '=', 'Nicollas']
			])
			->orWhere([
				     ['name', '=', 'Nicolas']
			])->execute();

/** find user using the basic structure query */
$user = $userModel->whereRaw("name = 'Nicollas'")->execute();

/** find users with limit */
$user = $userModel->limit(5)->execute();

/** find users with limit & offset */
$user = $userModel->limit(5)->offset(5)->execute();

/** find users with skip & take | the same as limit & offset */
$user = $userModel->take(5)->skip(5)->execute();

/** find users with orderBy. second parameter optional, default ASC */
$user = $userModel->orderBy('id', 'DESC')->orderBy('name')->execute();

/** find users and return results as attributes. EXAMPLE: $user->name instead of $user['name'] */
$user = $userModel->find()->execute(true); 

/** find users with specific columns. */
$user = $userModel->find()->only(['name', 'id', 'email'])->execute();

/** find users creating exceptions in columns. */
$user = $userModel->find(5)->except(['password'])->execute();

/** search in other database table */
$user = (new User())->useTable('posts')->find()->where([['owner_id', '=', $user->id]])->execute();

/** debug query for possible errors | return string */
$user = $userModel->whereRaw("uuid = 'f031b537-672f-4fba-b8a6-af45e778ad93'")->debugQuery();

/** group by method */
$user = $userModel->groupBy('id');
  • Note: except() method does not work chained with the execute(true) method, only execute() without parameter true.

  • Note: except() method only works when looking for specific information, in multidimensional arrays it does not work. This will be fixed soon.

  • All methods are friendly to each other, that means you can make complex queries. Real example:

/** Search for a user's posts varying between the privacy in which it was saved */
/** You can pass false as a fourth argument, the class will understand that you are trying to relate tables and will not put single quotes */

$posts = (new User())->useTable('posts p, users u')
                             ->where([['u.id', '=', $user['id'] ?? $visit['id']],
                                      ['u.id', '=', 'p.user_id', false], /** example of the fourth argument for relating tables */
                                      ['p.privacity', '<=', isset($privacity) && is_array($privacity) ? 3 : ($visit['url'] != $flag ? 1 : 4)]])
                             ->only(['p.*', 'u.name', 'u.url', 'u.i_profile'])
                             ->limit(10)
                             ->orderBy('p.id')
                             ->execute();

destroy

use Models\User;

$userModel = new User();
$user = $userModel->find(3)->execute(true);

    /** @return null|bool */
    if($user->destroy()) {
        echo "Success delete!";
    }
  • Note: To delete an information, you need to be aware that there is a reference to that information, that is, the primary key.

save (update)

use Models\User;

$userModel = new User();
$user = $userModel->find(5)->execute(true);
$user->name = "Other name";
$user->email = "[email protected]";

    /** @return null|bool */
    if($user->save()) {
        echo "Success!";
    }
  • Note: To save an information, you need to be aware that there is a reference to that information, that is, the primary key.
  • OBS: You can use the only() method to pull only the necessary information, but when editing, you can pass any column that exists in the database table and the system will proceed to treat and insert it. Example:
use Models\User;

$userModel = new User();
$user = $userModel->find(8)->only(['id', 'name'])->execute(true);
$user->name = "Russian Gabolev";

$user->email = "[email protected]";
/** This informations was not called from the database, but they exist. */
$user->updated_at = time();

    /** @return null|bool */
    if($user->save()) {
        echo "Success!";
    }
  • OBS2: In case of failure, it will return NULL, if completed, it will return true.

create (insert)

use Models\User;

    $userModel = new User();
    $user = $userModel->request([
        "name" => "Dr. Haylie Bahringer",
        "email" => '[email protected]', 
        "password" => 123456 // Encrypt before sending to the database
    ])->create();

It is also possible by passing a direct array:

use Models\User;

    $userModel = new User();
    $_POST = [
        "name" => "Hadjei Moccab",
        "email" => "[email protected]",
        "password" => 123456 // Encrypt before sending to the database
    ];
    $user = $userModel->request($_POST)->create();
  • OBS2: In case of failure, it will return NULL, if completed, it will return true.

Others methods

use Models\User;

    $userModel = new User();
    $user = $userModel->find(18)->execute(true);
    
    /** @return string | @param string $hash, @param Array $options */
    $user->password = $userModel->hashFormat($_POST['password']);
    
    /** @return string | @param string $url */
    $user->home = $userModel->urlFormat('Dr. John,Sik!@'); // dr-john-sik
    
    /** @return bool | @param string $email */
    if(!$userModel->validateEmail($_POST['email'])) {
        echo "Invalid email!";
    }
    
    /** @return bool | @param string $pass */
    if(!$userModel->validatePassword($_POST['password'])) {
        echo "Invalid password!";
    }
    
    /** @return bool | @param string $phone */
    if(!$userModel->validatePhone($_POST['telephone'])) {
        echo "Invalid telephone!";
    }
    
    /** @return bool | @param int $size */
    $user->recovery_token = $userModel->aleatoryToken(15);
    
    $user->save()
  • Guide to the above methods:
  • hashFormat: Encrypt a password using the native password_hash function.
  • urlFormat: Formats a string to a friendly url.
"Pác^kà@gê Sí#mp%lePHP" -> "pac-ka-ge-si-mp-lephp"
  • validateEmail: Validates that the email entered is valid. All true:
  • validatePassword: Checks whether the password contains an uppercase and lowercase letter, a special character, a number, if it is greater than 6 characters and less than 20.
123456 // false
QUASE123! // false
#OpA1 // false
#essaSenhaEGrande1234 // false
#OpA1? // true
Foi123! // true
  • validatePhone: Checks whether the phone number you entered is valid. (hyphen not required)
(00)0000-0000
(00)00000-0000
0000-0000
00000-0000
  • aleatoryToken: Generates a random string with the given size.

Errors during Execution

When an error is generated by SimplePHP, it will appear in the directory configured in the folder configuration, the report is generated by the monolog package.

Authors

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].