PHP 全局包

dev-main 2024-01-18 11:49 UTC

This package is not auto-updated.

Last update: 2024-09-27 13:13:10 UTC


README

Build Status Packagist Version (custom server) Packagist Downloads (custom server) GitHub

安装

使用composer安装

  composer require fort/php

在您的index.php或应用的入口点中添加以下代码;

<?php
require_once __DIR__ . "/vendor/autoload.php";
\Dotenv\Dotenv::createImmutable(__DIR__)->load();
 

可用的PHP函数

目录

数据库

要开始使用数据库支持,您必须在项目根目录中创建一个.env文件,并设置如下数据库凭据

DB_DATABASE=fort_project
DB_PORT=3306
DB_HOST=localhost
DB_USER=sam
DB_PASSWORD=sammyabc

测试数据库连接

测试数据库是否成功连接

<?php
use Velstack\PHP\Support\DB;

DB::connect();

// PDO Object: connected

插入记录

在数据库中插入或创建新记录

<?php
use Velstack\PHP\Support\DB;
use Carbon\Carbon;

DB::insert('users', [
 'name'=> 'Phil Everette',
 'email'=> 'pever@example.com',
 'phone'=> '0205550368',
 'created_at'=> Carbon::now() // fort/php already ships with carbon
]);

// @return (bool) true, false otherwise

更新记录

更新数据库中的特定记录。

<?php
use Velstack\PHP\Support\DB;
use Carbon\Carbon;

DB::update('users', 1, [
 'name'=> 'Sam Everette',
 'email'=> 'pever@example.com',
 'phone'=> '0205550368',
 'created_at'=> Carbon::now()  
]);

// 1 is the id of the record to update
// @return (bool) true, false otherwise

事务

开始数据库事务。

<?php
use Velstack\PHP\Support\DB;
 

public function createInvoice()
{
  try
   {
  DB::beginTransaction();
  //start some database queries
  DB::commit();
  // commit the queries
 }
 
 catch (Exception $exception)
 {
   DB::rollBack();
  // rollback the transaction in case of error
 }
}

查询

对数据库运行查询。

<?php
use Velstack\PHP\Support\DB;

$unpaidOrders = DB::table('orders')
  ->where('payment_status', '=', 'unpaid')
  ->orderBy('id', 'desc')
  ->get();
  
foreach ($unpaidOrders as $item){
  echo  $item['amount'];
}

原始查询

<?php
use Velstack\PHP\Support\DB;

$items = DB::rawQuery("SELECT users.id FROM users, 
 INNER JOIN orders ON users.id = orders.user_id")->get();
  
foreach ($items as $item){
 // echo ... ;
}

Select

<?php
use Velstack\PHP\Support\DB;

$adult = DB::table('users')
  ->select(['name', 'age'])
  ->where('age', '>', 18)
  ->orderBy('id', 'desc')
  ->get();
  
foreach ($adult as $individual){
  echo  $individual['age'];
}

所有

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->all();
// @returns all invoices

First

<?php
use Velstack\PHP\Support\DB;

DB::table('users')->where('email', '=','sam@example.com')->first();
// @returns the record in the query set

Where

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->where('amount_paid', '<', 1)->get();

OrWhere

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->where('amount_paid', '<', 1)
  ->orWhere('amount_paid', '=', false)
  ->get();

Sum

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->sum('amount_paid');
// @returns (int|float) a sum of the specified column

Count

<?php
use Velstack\PHP\Support\DB;

  DB::table('orders')->count();
  // @returns total number of orders

Max

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->max('amount');
// @returns (int|float) the highest number in the column

Min

<?php
use Velstack\PHP\Support\DB;

DB::table('invoices')->min('amount');
// @returns (int|float) the smallest number in the column

HTTP 请求

POST 请求

<?php
 use Velstack\PHP\Support\Http;
 
 Http::post('https://api.velstack.com/send',[$data],
            ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"];

GET 请求

<?php
 use Velstack\PHP\Support\Http;
 
 Http::get('https://api.velstack.com/resource', 
            ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],
            ['timeout'=> 20, 'return_transfer'=> true, 'maxredirs'=> 10, 'encoding'=> ""]);

Put/Patch 请求

<?php
 use Velstack\PHP\Support\Http;
 
 Http::put('https://api.velstack.com/resource', [$data],
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],

DELETE 请求

<?php
 use Velstack\PHP\Support\Http;
 
 Http::delete('https://api.velstack.com/resource', 
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],

PostMultipart 请求

<?php
 use Velstack\PHP\Support\Http;
 
 Http::asPostMultipart('https://api.velstack.com/send', [$data],
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY"]
             );

字符串辅助函数

Str valueExist

<?php
use Velstack\PHP\Str;

$haystack = array('FORT', 'Everette', 'Mike');
// returns true if the needle exist in case insensitive, false otherwise
Str::valueExist($haystack, 'foRT');
 // true

Str contains

<?php
use Velstack\PHP\Str;

$slice = Str::contains('I was raised in Ghana', 'Ghana');
// 'true'

Str containsAll

<?php
use Velstack\PHP\Str;

$string = Str::containsAll('My dad is from UK but i live in the US', ['UK', 'US']);

// 'true'

Str after

<?php
use Velstack\PHP\Str;

$slice = Str::after('His name is fort', 'His name');
// ' is fort'

Str afterLast

<?php
use Velstack\PHP\Str;

$slice = Str::afterLast('app\Http\Controllers\Controller', '\\');
// 'Controller'

Str before

<?php
use Velstack\PHP\Str;

$slice = Str::before('He is married', 'married');
// 'He is'

Str beforeLast

<?php
use Velstack\PHP\Str;

$slice = Str::beforeLast('He is married', 'is');
// 'He'

Str between

<?php
use Velstack\PHP\Str;

$slice = Str::between('He was born in March', 'He', 'March');
// 'was born in'

Str replace

<?php
use Velstack\PHP\Str;


$string = 'Transporter is a brilliant !';

$replaced = Str::replace('brilliant', 'genius', $string);

// Transporter is a genius !

Str charAt

<?php
use Velstack\PHP\Str;


$string = 'Transporter !';

$char = Str::charAt($string, 3);

// t

Str endsWith

<?php
use Velstack\PHP\Str;


$string = 'Everette is 1 year old';

$string = Str::endsWith($string, 'old');

// true

Str finish

<?php
use Velstack\PHP\Str;


$string = 'Everette is 1 year old';

$string = Str::finish($string, '!');

// Everette is 1 year old!

Str is

Str::is方法用于确定给定的字符串是否与给定的模式匹配。可以使用星号作为通配符值

<?php
use Velstack\PHP\Str;


$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

Str isUuid

<?php
use Velstack\PHP\Str;


$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

Str length

<?php
use Velstack\PHP\Str;


$isUuid = Str::length('Velstack');

// 8

Str words

<?php
use Velstack\PHP\Str;

 Str::words('Though he came, he could not make it.', 3, ' >>>');

// Though he came, >>>

Str wordCount

<?php
use Velstack\PHP\Str;

 Str::words('He was born in July');

// 5

Str limit

<?php
use Velstack\PHP\Str;


$truncated = Str::limit('He is a good man', 4, ' ...');

// He is ...

Str padBoth

<?php
use Velstack\PHP\Str;

$padded = Str::padBoth('sammy', 10, '_');

// 'sammy'

$padded = Str::padBoth('James', 10);

// '  sammy   '

Str padLeft

<?php
use Velstack\PHP\Str;


$padded = Str::padLeft('sammy', 6, '@');

// @sammy'

$padded = Str::padLeft('sammy', 6);

// '    sammy'

Str padRight

<?php
use Velstack\PHP\Str;

$padded = Str::padRight('sammy', 10, '-');

// 'sammy-----'

$padded = Str::padRight('sammy', 10);

// 'sammy     '

Str random

<?php
use Velstack\PHP\Str;

$random = Str::random(5);

// 3Cewm

Str uuid

<?php
use Velstack\PHP\Str;

$output = Str::uuid();

// a0a2a2d2-0b87-4a18-83f2-2529882be2de

Str isAscii

<?php
use Velstack\PHP\Str;

$isAscii = Str::isAscii('Accra');

// true

$isAscii = Str::isAscii('ü');

// false

Str isUuid

<?php
use Velstack\PHP\Str;

$string = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$string = Str::isUuid('Accra');

// false

Str upper

<?php
use Velstack\PHP\Str;


$converted = Str::upper('fort');

// FORT

Str lower

<?php
use Velstack\PHP\Str;


$converted = Str::lower('FORT');

// fort

Str title

<?php
use Velstack\PHP\Str;


$converted = Str::title('how to make money from home');

// How To Make Money From Home

Str slug

<?php
use Velstack\PHP\Str;


$converted = Str::slug('how to make money from home','-');

// How-To-Make-Money-From-Home

Str snake

<?php
use Velstack\PHP\Str;


$output = Str::snake('FootBall', '_');

// Foot_Ball

Str studly

<?php
use Velstack\PHP\Str;

$output = Str::studly('foo_bar');

// FooBar

Str kebab

<?php
use Velstack\PHP\Str;


$output = Str::kebab('fooBar');

// foo-bar

Str mask

<?php
use Velstack\PHP\Str;


$string = Str::mask('samuelfort@example.com', '*', -15, 3);

// sam***@example.com

Str start

Str::start方法如果字符串不以前面给定的值开始,则向字符串中添加单个该值实例

<?php
use Velstack\PHP\Str;

$adjusted = Str::start('sammy_fort', '@');

// @sammy_fort

$adjusted = Str::start('@fortameyaw', '@');

// @fortameyaw

Str reverse

<?php
use Velstack\PHP\Str;

$reversed = Str::reverse('Hello');

// olleH

Str substr

<?php
use Velstack\PHP\Str;


$converted = Str::substr('The Symfony PHP Framework', 4, 7);

// Laravel

Str substrCount

<?php
use Velstack\PHP\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str substrReplace

<?php
use Velstack\PHP\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str replaceFirst

<?php
use Velstack\PHP\Str;

$string  = 'He is lazy';

$output = Str::replaceFirst('He', 'Tom', $string);

// Tom is lazy

Str replaceLast

<?php
use Velstack\PHP\Str;

$string  = 'Kwaku is a handsome boy';

$output = Str::replaceLast('a', 'the', $string);

// Kwaku is the handsome boy

Str lcfirst

<?php
use Velstack\PHP\Str;

$output = Str::lcfirst('Handsome');

// handsome

Str ucfirst

<?php
use Velstack\PHP\Str;

$output = Str::ucfirst('beautiful');

// Beautiful

数组辅助函数

Arr Maximum

<?php
 use Velstack\PHP\Arr;
 
$array = ['Transporter'=> 3, 'Phil'=> 0, 'Ever'=> 1];

print_r(Arr::maximum($array));

// Transporter

Arr Minimum

<?php
 use Velstack\PHP\Arr;
 
$array = ['Transporter'=> 3, 'Phil'=> 1, 'Ever'=> 0];

print_r(Arr::minimum($array));

// Ever

Arr valueExist

在数组中检查needle是否存在,忽略大小写。如果存在返回true,否则返回false。

<?php
 use Velstack\PHP\Arr;
 
$array = ['Transporter', 'Phil', 'Ever'];

 print_r(Arr::valueExist($array, 'FORT'));

// true

Arr accessible

<?php
 use Velstack\PHP\Arr;
 
$array = ['Transporter' => 1, 'Phil'=> 2, 'Ever' => 3];

 print_r(Arr::accessible($array));

// true

$array = "fort";

 print_r(Arr::accessible($array));

// false

Arr whereNotNull

<?php
 use Velstack\PHP\Arr;
 
$array = [0, null];
 
$filtered = Arr::whereNotNull($array);
 
// [0 => 0]

Arr where

<?php
 use Velstack\PHP\Arr;
 
$array = [100, '200', '300', '400', '500'];
 
$filtered = Arr::where($array, function ($value, $key) {
    return is_numeric($value);
});
 
// [0 => '100']

Arr first

<?php
 use Velstack\PHP\Arr;
 
$array = [1, 15, 35];
 
$first = Arr::first($array, function ($value, $key) {
    return $value >= 20;
});
 
// 35

Arr last

<?php
 use Velstack\PHP\Arr;
 
$array = [1, 15, 35, 40];
 
$first = Arr::last($array, function ($value, $key) {
    return $value >= 40;
});
 
// 40
 
 

Arr wrap

<?php
 use Velstack\PHP\Arr;
 
$string = 'PHP is fun';
 
$array = Arr::wrap($string);
 
// ['PHP is fun']

Arr add

Arr::shuffle方法随机打乱数组中的项目

<?php
 use Velstack\PHP\Arr;
 
$array = Arr::add(['name' => 'Desk'], 'price', 100);
 
// ['name' => 'Desk', 'price' => 100]
 
$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
 
// ['name' => 'Desk', 'price' => 100]

Arr set

<?php
 use Velstack\PHP\Arr;
 
$array = ['orders' => ['desk' => ['price' => 100]]];
 
Arr::set($array, 'orders.desk.price', 200);
 
// ['orders' => ['desk' => ['price' => 200]]]

Arr shuffle

Arr::shuffle方法随机打乱数组中的项目

<?php
 use Velstack\PHP\Arr;
 
$array = Arr::shuffle([1, 2, 3, 4, 5]);
 
// [3, 2, 5, 1, 4] - (generated randomly)

Arr collapse

<?php
 use Velstack\PHP\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
 
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Arr divide

Arr::divide 方法返回两个数组:一个包含给定数组的键,另一个包含值

<?php
 use Velstack\PHP\Arr;
 
[$keys, $values] = Arr::divide(['name' => 'Desk']);
 
// $keys: ['name']
 
// $values: ['Desk']

Arr except

<?php
 use Velstack\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
 
$filtered = Arr::except($array, ['price']);
 
// ['name' => 'Desk']

Arr exists

<?php
 use Velstack\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
$array = ['name' => 'John Doe', 'age' => 17];
 
$exists = Arr::exists($array, 'name');
 
// true

$exists = Arr::exists($array, 'salary');
 
// false

Arr flatten

<?php
 use Velstack\PHP\Arr;
 
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
 
$flattened = Arr::flatten($array);
 
// ['Joe', 'PHP', 'Ruby']
 
// false

Arr forget

<?php
 use Velstack\PHP\Arr;
 
$array = ['products' => ['desk' => ['price' => 100]]];
 
Arr::forget($array, 'products.desk');
 
// ['products' => []]

Arr get

<?php
 use Velstack\PHP\Arr;
 
$array = ['products' => ['desk' => ['price' => 100]]];
 
$price = Arr::get($array, 'products.desk.price');
 
// 100

Arr has

<?php
 use Velstack\PHP\Arr;
 
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
 
$contains = Arr::has($array, 'product.name');
 
// true
 
$contains = Arr::has($array, ['product.price', 'product.discount']);
 
// false

Arr hasAny

<?php
 use Velstack\PHP\Arr;
 
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
 
$contains = Arr::hasAny($array, 'product.name');
 
// true
 
$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
 
// true
 
$contains = Arr::hasAny($array, ['category', 'product.discount']);
 
// false

Arr isAssoc

<?php
 use Velstack\PHP\Arr;
 
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
 
// true
 
$isAssoc = Arr::isAssoc([1, 2, 3]);
 
// false

Arr prepend

<?php
 use Velstack\PHP\Arr;
 
$array = ['one', 'two', 'three', 'four'];
 
$array = Arr::prepend($array, 'zero');
 
// ['zero', 'one', 'two', 'three', 'four']

$array = ['price' => 100];
 
$array = Arr::prepend($array, 'Desk', 'name');
 
// ['name' => 'Desk', 'price' => 100]

Arr pluck

<?php
 use Velstack\PHP\Arr;
 
$array = [
    ['product' => ['id' => 1, 'name' => 'Drink']],
    ['product' => ['id' => 2, 'name' => 'Wheat']],
];
 
$names = Arr::pluck($array, 'product.name');
 
// ['Drink', 'Wheat']

Arr only

<?php
 use Velstack\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
 
$slice = Arr::only($array, ['name', 'price']);
 
// ['name' => 'Desk', 'price' => 100]

Arr pull

<?php
 use Velstack\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
 
$name = Arr::pull($array, 'name');
 
// $name: Desk
 
// $array: ['price' => 100]

Arr query

<?php
 use Velstack\PHP\Arr;
 
$array = [
    'name' => 'Mike',
    'order' => [
        'column' => 'created_at',
        'direction' => 'desc'
    ]
];
 
 $q = Arr::query($array);
 
// name=Mike&order[column]=created_at&order[direction]=desc

Arr random

<?php
 use Velstack\PHP\Arr;
 
$array = [1, 2, 3, 4, 5];
 
$random = Arr::random($array);
 
// 4 - (retrieved randomly)

SMS

要开始使用 SMS 支持,您必须在 .env 文件中设置以下变量。 SMS_DRIVER 只能设置为 velstackvonage。这些是支持的驱动程序。

SMS_DRIVER=velstack
SMS_API_KEY=sk_test__
SMS_SECRET_KEY=
SMS_SENDER_ID=BUSINESS

发送 SMS

<?php
 use Velstack\PHP\Support\SMS;
 
 return SMS::send('+233205550368', 'Hello, API messaging is just awesome');

数学辅助工具

百分比

<?php
 use Velstack\PHP\Math;
 
 Math::percentage(1.5, 200);
 // 3

指数

<?php
 use Velstack\PHP\Math;
 
 Math::expo(2, 2);
 // 4

平方根

<?php
 use Velstack\PHP\Math;
 
 Math::sqrRoot(20);
  // 4.4721359549996

求和

<?php
 use Velstack\PHP\Math;
 
 Math::sum(11, 11);
 // 22

减法

<?php
 use Velstack\PHP\Math;
 
 Math::sub(10, 11);
 // -1

除法

<?php
 use Velstack\PHP\Math;
 
 Math::div(19, 5);
 // 3.8

乘法

<?php
 use Velstack\PHP\Math;
 
 Math::mul(21, 8);
 // 168

最大值

<?php
 use Velstack\PHP\Math;
 
 Math::max(2, 6, 4);
 // 6

最小值

<?php
 use Velstack\PHP\Math;
 
 Math::min(2, 6, 4);
 // 2

确保模型使用 DateFilters 特性

 

namespace App\Models;

use Velstack\Illuminate\Support\Eloquent\DateFilters;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    use HasFactory, DateFilters;
     

    protected $table = 'invoices';

     protected $fillable = [
        'user_id',
        'invoice_id',
        'customer',
        'shipping' ,
    ];

      
}

一旦在您的模型中实现了 DateFilters,您可以在控制器中像下面这样访问它们

 
namespace App\Http\Controllers\Subscription;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
 

class InvoiceController extends Controller
{
 

    public function getTodayInvoices()
    {

        return Invoice::today()->get();
        
        // all invoices created today
    }
    
    public function yesterday()
    {

        return Invoice::yesterday()->sum('amount');
        // sums yesterday invoices amount
    }
    
     public function week()
     {

        return Invoice::Last7Days()->get();
        // returns invoices of the last 7 days
    }
    
    
       public function two_weeks()
     {

        return Invoice::QuarterToDate()->get();
        // returns all invoices from last two weeks
    }
    
     public function this_month()
     {

        return Invoice::MonthToDate()->sum('amount');
        // returns invoices from the start of the current month 
    }
    
    public function last30days()
     {

        return Invoice::Last30Days()->get();
         // returns invoices created in the last 30 days.
     }
    
   
    
    public function this_year()
     {

        return Invoice::YearToDate()->get();
        // returns all invoices from the start of the year
    }
    
    
      public function last_year()
     {

        return Invoice::LastYear()->get();
        // returns all invoices from last year
    }
    
    
       public function last_quater()
     {

        return Invoice::LastQuarter()->get();
        // returns all invoices from last 3 months
    }  
}